Is there a way to globally change the default behaviors of bindings in wpf?

前端 未结 3 1719
甜味超标
甜味超标 2020-12-10 15:09

Is there a way to change the default behavior of bindings so i don\'t need to set \'UpdateSourceTrigger=PropertyChanged\' on each, in my case, textbox?

Might this b

3条回答
  •  佛祖请我去吃肉
    2020-12-10 16:05

    Like Pieter proposed i solved it with a inherited class like this:

    public class ActiveTextBox:TextBox
        {
            public ActiveTextBox()
            {
                Loaded += ActiveTextBox_Loaded;
            }
    
            void ActiveTextBox_Loaded(object sender, System.Windows.RoutedEventArgs e)
            {
                Binding myBinding = BindingOperations.GetBinding(this, TextProperty);
                if (myBinding != null && myBinding.UpdateSourceTrigger != UpdateSourceTrigger.PropertyChanged)
                {
                    Binding bind = (Binding) Allkort3.Common.Extensions.Extensions.CloneProperties(myBinding);
                    bind.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
                    BindingOperations.SetBinding(this, TextBox.TextProperty, bind);
                }
            }
        }
    

    and this helpmethod:

    public static object CloneProperties(object o)
            {
                var type = o.GetType();
                var clone = Activator.CreateInstance(type);
                foreach (var property in type.GetProperties())
                {
                    if (property.GetSetMethod() != null && property.GetValue(o, null) != null)
                        property.SetValue(clone, property.GetValue(o, null), null);
                }
                return clone;
            }
    

    Any suggestion how to solve it better?

提交回复
热议问题