views:

114

answers:

2

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"));
+1  A: 

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.

Javier Morillo
That confuses the domain object, adding UI specific behaviour to it.
SnOrfus
Right, that´s why I prefer Adam´s answer :-) thanks!
Javier Morillo
+1 still though. It is a solution to the problem, just not what I was looking for. Thank you.
SnOrfus
+3  A: 

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.

Adam Robinson
+1 I like your first option, didn´t know it :-)
Javier Morillo
I was aware of option 2, and I probably should have mentioned that I didn't want to put UI logic in my domain model, which is why I didn't go with it. That said, I did implement the first option successfully. Thank you very much. I want to point out for anyone who might see this in the future: You cannot add that binding to multiple controls, one must be created per UI control (Which is what I was wanting do do).
SnOrfus