开发者

binding a usercontrol to the opposite of a bool property

开发者 https://www.devze.com 2022-12-23 00:53 出处:网络
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)

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 th开发者_StackOverflow社区e 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.


Based on Adam's answer I wrote a small helper class:

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);
    }
}

Now you can use it like this:

label1.DataBindings.Add(new NegateBinding("Visible", otherObject, "HasData"));


To do this, I´d do a readonly property named NotSomeBool, in the same class where you have the property SomeBool, and bind to this property instead.

0

精彩评论

暂无评论...
验证码 换一张
取 消