将用户控件绑定到bool属性的对面 [英] binding a usercontrol to the opposite of a bool property
问题描述
很简单:我正在寻找与这个一样的功能,但是在winforms。谷歌似乎拉起来的一切都是wpf具体(即我不想引用presentationframework.dll)
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)
如果你不想阅读链接:
以下是我想要做的意图的表示,虽然它显然不起作用。 p>
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"));
推荐答案
您有两个选择:
- 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
第一个选项是更干净的IMO,因为它不强制您的类的API遵循您的UI设计,尽管第二个选项(稍微)更容易。
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.
选项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设计。
Again, I very much favor option 1, since option 2 requires that you tailor your class to your UI design.
这篇关于将用户控件绑定到bool属性的对面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!