剛剛開始使用C#中的數據綁定並尋求一些幫助。當將組合框的SelectedItem綁定到BusinessObject的MyEnumVar的行執行時,下面的綁定語句中斷(Visible屬性停止與MyBool & MyBoolInverse停止切換)。直接綁定到對象而不是BindingSource,或綁定到SelectedValue而不是SelectedItem,具有相同的效果。此外,MyEnumVar的值不會隨着對組合框的選擇而改變。我究竟做錯了什麼?多個控件和單個對象之間的DataBinding
public partial class Form1 : Form
{
BindingSource bs = new BindingSource();
private BusinessObject bo = new BusinessObject();
public Form1()
{
InitializeComponent();
bs.DataSource = bo;
// Checkbox determines what type of dialog to display.
boolCheckBox.DataBindings.Add("Checked", bs, "MyBool", true,
DataSourceUpdateMode.OnPropertyChanged);
trueBox.DataBindings.Add("Visible", bs, "MyBoolInverse");
falseComboBox.DataBindings.Add("Visible", bs, "MyBool");
falseBox.DataBindings.Add("Visible", bs, "MyBool");
falseButton.DataBindings.Add("Visible", bs, "MyBool");
myEnumComboBox.DataSource = Enum.GetValues(
typeof(BusinessObject.MyEnum));
// Line below breaks above bindings, same for SelectedValue.
myEnumComboBox.DataBindings.Add("SelectedItem", bs, "MyEnumVar");
}
}
class BusinessObject : INotifyPropertyChanged
{
public enum MyEnum { RED, BLU }
MyEnum _MyEnumVar;
public MyEnum MyEnumVar
{
get { return _MyEnumVar; }
set
{
if (value != _MyEnumVar)
{
_MyEnumVar = value;
NotifyPropertyChanged("MyEnumVar");
}
}
}
private bool _MyBool;
public bool MyBool
{
get { return _MyBool; }
set
{
if (value != _MyBool)
{
_MyBool = value;
MyBoolInverse = !value;
NotifyPropertyChanged("MyBool");
}
}
}
private bool _MyBoolInverse;
public bool MyBoolInverse
{
get { return _MyBoolInverse; }
private set
{
if (value != _MyBoolInverse)
{
_MyBoolInverse = value;
NotifyPropertyChanged("MyBoolInverse");
}
}
}
public BusinessObject()
{
MyBoolInverse = !MyBool;
MyEnumVar = MyEnum.BLU;
}
// Boilerplate INotifyPropertyChanged implementation & helper.
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName = "")
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
你沒有說錯誤是什麼? – clearpath 2013-05-03 14:12:12
編輯過,會發生什麼情況是Visible屬性在啓用最後一個綁定語句時停止在MyBool&MyBoolInverse上進行切換。 – CANTPRO 2013-05-03 14:18:34
因此,爲ComboBox的SelectedValueChanged事件設置委託匿名方法按預期工作,Visible屬性綁定仍然有效。反方向與PropertyChanged事件的代表將在激活時破壞表單。我相信是這樣的,因爲我沒有將枚舉強制轉換爲適當的類型以分配給SelectedItem或SelectedValue。 – CANTPRO 2013-05-03 16:37:13