将usercontrol绑定到bool属性的反面
非常简单:我希望在winforms中做同样的事情。 谷歌似乎拔出的所有东西都是特定的wpf(即我不想引用presentationframework.dll)
如果您不想阅读链接,请说明:
以下是我想要做的意图的表示,虽然它显然不起作用。
CheckBox1.DataBindings.Add(new Binding("Checked", this.object, "!SomeBool"));
你有两个选择:
- 手动创建
Binding
对象并附加到Format
和Parse
事件并交换每个事件中的值。 - 在类上创建一个仅反转目标属性逻辑的附加属性
第一个选项是更清洁,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);
选项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");
同样,我非常赞成选项1,因为选项2要求您根据UI设计定制类。
根据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); } }
现在您可以像这样使用它:
label1.DataBindings.Add(new NegateBinding("Visible", otherObject, "HasData"));
为此,我将在具有属性NotSomeBool
的同一个类中执行名为NotSomeBool
的只读属性,并绑定到此属性。