将usercontrol绑定到bool属性的反面

Ste*_*ers 16 c# data-binding winforms

很简单:我希望做的一样,但WinForms的.谷歌似乎拔出来的一切都是特定的wpf(即我不想引用presentationframework.dll)

如果您不想阅读链接,请说明:

以下是我想要做的意图的表示,虽然它显然不起作用.

CheckBox1.DataBindings.Add(new Binding("Checked", this.object, "!SomeBool"));
Run Code Online (Sandbox Code Playgroud)

Ada*_*son 23

您有两种选择:

  1. Binding手动创建对象并附加到FormatParse事件并交换每个对象中的值.
  2. 在类上创建一个仅反转目标属性逻辑的​​附加属性

第一个选项是清洁,IMO,因为它不会强制您的类的API遵循您的UI设计,尽管第二个选项(略微)更容易.

选项1的示例

private void SwitchBool(object sender, ConvertEventArgs e)
{ 
    e.Value = !((bool)e.Value);
}

...

Binding bind = new Binding("Checked", this.object, "SomeBool");

bind.Format += SwitchBool;
bind.Parse += SwitchBool;

CheckBox1.DataBindings.Add(bind);
Run Code Online (Sandbox Code Playgroud)

选项2的示例

public class SomeClass
{
    public bool SomeBool { get; set; }

    public bool NotSomeBool
    {
        get { return !SomeBool; }
        set { SomeBool = !value; }
    }
}

...

CheckBox1.DataBindings.Add("Checked", this.object, "NotSomeBool");
Run Code Online (Sandbox Code Playgroud)

同样,我非常赞成选项1,因为选项2要求您根据UI设计定制类.


Tom*_*lny 10

根据Adam的回答,我写了一个小助手类:

class NegateBinding
{
    string propertyName;
    object dataSource;
    string dataMember;
    public NegateBinding(string propertyName, object dataSource, string dataMember)
    {
        this.propertyName = propertyName;
        this.dataSource = dataSource;
        this.dataMember = dataMember;
    }

    public static implicit operator Binding(NegateBinding eb)
    {
        var binding = new Binding(eb.propertyName, eb.dataSource, eb.dataMember, false, DataSourceUpdateMode.OnPropertyChanged);
        binding.Parse += new ConvertEventHandler(negate);
        binding.Format += new ConvertEventHandler(negate);
        return binding;
    }

    static void negate(object sender, ConvertEventArgs e)
    {
        e.Value = !((bool)e.Value);
    }
}
Run Code Online (Sandbox Code Playgroud)

现在您可以像这样使用它:

label1.DataBindings.Add(new NegateBinding("Visible", otherObject, "HasData"));
Run Code Online (Sandbox Code Playgroud)