一个用户控件绑定到一个布尔属性相反 [英] binding a usercontrol to the opposite of a bool property

查看:113
本文介绍了一个用户控件绑定到一个布尔属性相反的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很简单:我希望做的一样但在的WinForms。那谷歌似乎拉起一切都是具体的WPF(即我不想引用presentationframework.dll)



解释,如果你不想阅读链接:



下面是想我做的,但它显然是行不通的意图的表示

  CheckBox1.DataBindings.Add(新绑定(选中,this.object,SomeBool!)); 


解决方案

您有两种选择:




  1. 手动创建绑定对象,并连接到的 格式 和的 解析 事件和交换在每个值

  2. 创建的类附加属性,只是颠倒了预期的属性



<的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:

  1. Create the Binding object manually and attach to the Format and Parse events and swap the value in each.
  2. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆