WPF:定义绑定的默认值

PBe*_*ger 24 wpf xaml binding templates default

在WPF中,我希望能够模板化默认情况下应用绑定的方式.

例如,我想写:

Text="{Binding Path=PedigreeName}"
Run Code Online (Sandbox Code Playgroud)

但就好像我打字了一样:

Text="{Binding Path=PedigreeName, Mode=TwoWay, UpdateSourceTrigger=LostFocus, NotifyOnValidationError=True, ValidatesOnDataErrors=True, ValidatesOnExceptions=True}" 
Run Code Online (Sandbox Code Playgroud)

任何的想法 ?

谢谢,

  • 帕特里克

Joe*_*ite 26

使用带有PropertyMetadata 的DependencyProperty.Register重载之一.传递FrameworkPropertyMetadata的实例并设置其属性.

public class Dog {
    public static readonly DependencyProperty PedigreeNameProperty =
        DependencyProperty.Register("PedigreeName", typeof(string), typeof(Dog),
            new FrameworkPropertyMetadata() {
                BindsTwoWayByDefault = true,
                DefaultUpdateSourceTrigger = UpdateSourceTrigger.LostFocus
            }
        );
Run Code Online (Sandbox Code Playgroud)

我没有随意看到设置NotifyOnValidationError,ValidatesOnDataErrors或ValidatesOnExceptions的默认值的方法,但我还没有使用它来确定要查找的内容; 他们可能在那里.


Tho*_*que 16

除了Joe White的好答案之外,您还可以创建一个继承自Binding的类,并设置您需要的默认属性值.例如 :

public class TwoWayBinding : Binding
{
    public TwoWayBinding()
    {
        Initialize();
    }

    public TwoWayBinding(string path)
      : base(path)
    {
        Initialize();
    }

    private void Initialize()
    {
        this.Mode = BindingMode.TwoWay;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @vines:`Text ="{my:TwoWayBinding Path = PedigreeName}"` (2认同)