WPF Property Data binding to negate the property

后端 未结 4 1739
忘掉有多难
忘掉有多难 2020-12-16 10:13

Is there any way to change the value of property at runtime in WPF data binding. Let\'s say my TextBox is bind to a IsAdmin property. Is there anyway I can change that prope

4条回答
  •  猫巷女王i
    2020-12-16 10:33

    You can't bind to !Property, but you could create a new Binding with an appropriate IValueConverter and change out the entire Binding at runtime. The key is the BindingOperations class, which allows you to change the binding on a particular DependencyProperty.

        public static void InvertBinding(DependencyObject target, DependencyProperty dp)
        {
            //We'll invert the existing binding, so need to find it
            var binding = BindingOperations.GetBinding(target, dp);
            if (binding != null)
            {
                if (binding.Converter != null)
                    throw new InvalidOperationException("This binding already has a converter and cannot be inverted");
                binding.Converter = new InvertingValueConverter(); //This would be your custom converter
    
                //Not sure if you need this step, but it will cause the binding to refresh
                BindingOperations.SetBinding(target, dp, binding);
            }
        }
    

    This should give you a general idea; I wouldn't use this for production code, as you'd probably want to generalize it to toggle the converter or whatever else you need to change out at runtime. You could also avoid changing the binding entirely by creating a new property you bind to that encapsulates this 'switching' logic. The last option is probably the best.

提交回复
热议问题