binding a usercontrol to the opposite of a bool property

前端 未结 3 617
长情又很酷
长情又很酷 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 00:54

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

提交回复
热议问题