我想更好地瞭解數據綁定如何在.net中工作。我檢查this文章,我想出了這個代碼:C#中的數據綁定問題
public partial class Form1 : Form//, INotifyPropertyChanged
{
public event PropertyChangedEventHandler MyTextChanged;
[System.ComponentModel.Bindable(true)]
public string MyText
{
get { return textBox1.Text; }
set
{
textBox1.Text = value;
if (MyTextChanged != null)
MyTextChanged(this, new PropertyChangedEventArgs("MyText"));
}
}
MyClass myClass { get; set; }
public Form1()
{
InitializeComponent();
myClass = new MyClass();
Binding binding = new Binding("MyText", myClass, "Dic");
binding.Parse += new ConvertEventHandler(binding_Parse);
binding.Format += new ConvertEventHandler(binding_Format);
DataBindings.Add(binding);
myClass.AddStuff("uno", "UNO");
}
void OnMyTextChanged(PropertyChangedEventArgs e)
{
if (MyTextChanged != null) MyTextChanged(this, e);
}
void binding_Format(object sender, ConvertEventArgs e)
{
if (e.Value is Dictionary<string, string>)
{
Dictionary<string, string> source = (Dictionary<string, string>)e.Value;
e.Value = source.Count.ToString();
}
}
void binding_Parse(object sender, ConvertEventArgs e)
{
MessageBox.Show(e.DesiredType.ToString());
}
private void changemyClassButton_Click(object sender, EventArgs e)
{
myClass.AddStuff(myClass.Dic.Count.ToString(), "'" + myClass.Dic.Count.ToString() + "'");
}
private void changeMyTextButton_Click(object sender, EventArgs e)
{
MyText = "1234";
}
}
public class MyClass : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public Dictionary<string, string> Dic { get; set; }
public MyClass()
{
Dic = new Dictionary<string, string>();
}
public void AddStuff(string key, string value)
{
Dic.Add(key, value);
if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Dic"));
}
}
我試圖綁定MyText
到myClass
。問題是功能binding_Parse
從未被調用。我知道我可以將textBox1.Text
直接綁定到myClass
,或者可能有其他可能的方法來做我想做的事情,但這只是一種實踐;我試圖理解更好的數據綁定。所以我想將一個自定義對象綁定到一個自定義屬性,這樣我就可以從頭到尾看到這個過程。自定義對象是myClass
,自定義屬性是MyText
。我嘗試了各種各樣的變體,例如執行INotifyPropertyChanged
,但我無法調用binding_Parse
(我希望在撥打changeMyTextButton_Click
時調用它)。我錯過了什麼嗎?
編輯: 說得簡單:我想寫一個屬性string MyText
用戶控件,然後用戶可以綁定到別的東西,以同樣的方式,你可以一個TextBox
的Text
屬性綁定到別的東西。所以我不想將一個控件的屬性綁定到一個對象,我想用一個屬性編寫一個控件,然後用戶可以綁定到一個對象。
你打算做什麼?用MyText屬性更新文本框內容?或強制binding_parse被執行? – 2010-10-21 20:27:01
我想將'MyText'綁定到'myClass.Dic',這樣每當'MyText'發生變化時'myClass.Dic'發生變化(我想''binding'調用''開始調用,因爲我會在其中設置'MyText'的新值),並且每當'myClass.Dic'改變時,'MyText'改變(這已經有效)。當myClass.Dic沒有特殊原因改變時,我選擇將MyText設置爲myClass.Dic.Count.ToString()。我只是想看到一個反映在另一個上的任何變化。我找到了[這篇] [1]文章,但它是針對糧食計劃署的。我無法找到一個Windows窗體。 [1]:http://msdn.microsoft.com/en-us/library/ms752347.aspx – Juan 2010-10-21 20:39:50
另一個例子是將'string str1'綁定到'string str2',以便每當'str1'發生變化時, str2'被設置爲'str1',每當'str2'改變時,'str1'被設置爲'str2'。全部通過使用標準的.net數據綁定。這將迫使我使用Format和Parse,並且我終於可以看到整個數據綁定週期是如何工作的。 – Juan 2010-10-21 20:44:29