binding a usercontrol to the opposite of a bool property

前端 未结 3 616
长情又很酷
长情又很酷 2021-02-19 00:39

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 presentation

3条回答
  •  悲&欢浪女
    2021-02-19 01:14

    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.

提交回复
热议问题