25

在 WPF 中,我希望能够对默认情况下如何应用我的绑定进行模板化。

例如,我想写:

Text="{Binding Path=PedigreeName}"

但就好像我输入了:

Text="{Binding Path=PedigreeName, Mode=TwoWay, UpdateSourceTrigger=LostFocus, NotifyOnValidationError=True, ValidatesOnDataErrors=True, ValidatesOnExceptions=True}" 

任何的想法 ?

谢谢,

  • 帕特里克
4

2 回答 2

28

使用采用 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
            }
        );

我没有立即看到设置 NotifyOnValidationError、ValidatesOnDataErrors 或 ValidatesOnExceptions 的默认值的方法,但我没有充分使用它来确定要查找的内容;他们可能在那里。

于 2009-07-07T20:41:34.740 回答
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;
    }
}
于 2009-07-07T20:46:39.567 回答