0

刚开始使用 C# 中的数据绑定并寻求帮助。当组合框的 SelectedItem 到 BusinessObject 的 MyEnumVar 的行绑定执行时,以下绑定语句中断(Visible 属性停止与 MyBool 和 MyBoolInverse 切换)。直接绑定到对象而不是 BindingSource,或者绑定到 SelectedValue 而不是 SelectedItem,具有相同的效果。此外,MyEnumVar 的值不会随着对组合框的选择而改变。我究竟做错了什么?

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));
        }
    }
}
4

1 回答 1

0

可见属性存在绑定问题。尝试手动“绑定”。类似的东西

trueBox.Visible = bo.MyBoolInverse;
bo.PropertyChanged += (s, e) => { 
  if(e.PropertyName == "MyBoolInverse") 
    trueBox.Visible = bo.MyBoolInverse; 
};

编辑:另外,绑定到MyEnumVar不起作用,因为它没有被声明为公共属性。

于 2013-05-03T14:24:00.650 回答