一个用户控件绑定到一个布尔属性相反 [英] binding a usercontrol to the opposite of a bool property
问题描述
很简单:我希望做的一样这但在的WinForms。那谷歌似乎拉起一切都是具体的WPF(即我不想引用presentationframework.dll)
的解释,如果你不想阅读链接:的
下面是想我做的,但它显然是行不通的意图的表示。 p>
CheckBox1.DataBindings.Add(新绑定(选中,this.object,SomeBool!));
您有两种选择:
<的p逻辑>第一个选项是清洁的,海事组织,因为它不强迫你的类的API来按照你的UI设计,虽然第二个选项是(略)更容易。
<选项1
私人无效SwitchBool(对象发件人,ConvertEventArgs E)
{$的strong>示例b $ b e.Value =((布尔)e.Value)!;
}
:
结合绑定=新的绑定(选中,this.object,SomeBool);
bind.Format + = SwitchBool;
bind.Parse + = SwitchBool;
CheckBox1.DataBindings.Add(绑定);
选项的示例2
公共类SomeClass的
{
公共BOOL SomeBool {搞定;组; }
公共BOOL NotSomeBool
{
{返回SomeBool!; !}
集合{SomeBool =价值; }
}
}
...
CheckBox1.DataBindings.Add(选中,this.object,NotSomeBool);
再次我非常赞成选项1,因为选项2,您需要调整您的类到你的UI设计。
Pretty straightforward: I'm looking to do the same as this but in winforms. Everything that google seems to pull up is wpf specific (ie. I don't want to reference presentationframework.dll)
Explained if you don't want to read the link:
The following is a representation of the intent of what I'd like to do, though it obviously doesn't work.
CheckBox1.DataBindings.Add(new Binding("Checked", this.object, "!SomeBool"));
You have two options:
- Create the
Binding
object manually and attach to theFormat
andParse
events and swap the value in each. - Create an additional property on the class that just reverses the logic of the intended property
The first option is cleaner, IMO, as it doesn't force your class's API to follow your UI design, though the second option is (marginally) easier.
Example of Option 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);
Example of Option 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");
Again, I very much favor option 1, since option 2 requires that you tailor your class to your UI design.
这篇关于一个用户控件绑定到一个布尔属性相反的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!