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

杀马特。学长 韩版系。学妹 提交于 2019-11-27 06:12:34

问题


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 be done via a ControlTemplate or Style?


回答1:


Maybe it's more suitable to override the defaults for your Bindings, you could use this one for that purpose:

http://www.hardcodet.net/2008/04/wpf-custom-binding-class

Then you define some CustomBinding class (setting appropriate defaults in the constructor) and a MarkupExtension 'CustomBindingExtension'. Then replace the bindings in your XAML by something like this:

Text="{CustomBinding Path=Xy...}"

I have successfully tried something similar with a binding that sets certain defaults for ValidatesOnDataError and NotifyOnValidationError, should work in your case as well. The question is if you are comfortable with replacing all your bindings, but you could automate this task.




回答2:


No. This behavior is handled by the DefaultUpdateSourceTrigger of the FrameworkPropertyMetadata class, which is passed when registering a DependencyProperty. It is possible to override this in an inherited class of TextBox and per binding, but not for every TextBox in the application.




回答3:


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?



来源:https://stackoverflow.com/questions/4076921/is-there-a-way-to-globally-change-the-default-behaviors-of-bindings-in-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!