【问题标题】:WPF : Define binding's defaultWPF:定义绑定的默认值
【发布时间】:2010-11-08 20:00:04
【问题描述】:

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

例如,我想写:

Text="{Binding Path=PedigreeName}"

但好像我输入了:

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

有什么想法吗?

谢谢,

  • 帕特里克

【问题讨论】:

    标签: wpf xaml binding templates default


    【解决方案1】:

    使用采用 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 的默认值的方法,但我没有充分使用它来确定要查找的内容;他们可能在那里。

    【讨论】:

    • 谢谢,好主意,但在我的例子中,Dog 类是在一个商业模型项目中。我不想为这个项目添加对 System.Windows 的依赖。我正在寻找的解决方案是朝着那个方向,比如把 在 App.xaml 中,但没有找到任何匹配...再次感谢!
    【解决方案2】:

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

    public class TwoWayBinding : Binding
    {
        public TwoWayBinding()
        {
            Initialize();
        }
    
        public TwoWayBinding(string path)
          : base(path)
        {
            Initialize();
        }
    
        private void Initialize()
        {
            this.Mode = BindingMode.TwoWay;
        }
    }
    

    【讨论】:

    • 谢谢,我最终以这种方式实现了它。 [代码] public class ValidationBinding : Binding { public ValidationBinding() { Initialize(); } public ValidationBinding(string path) : base(path) { Initialize(); } private void Initialize() { Mode = BindingMode.TwoWay; UpdateSourceTrigger = UpdateSourceTrigger.LostFocus; NotifyOnValidationError = true; ValidatesOnDataErrors = true; ValidatesOnExceptions = true; } } [/code]
    • @vines: Text="{my:TwoWayBinding Path=PedigreeName}"
    猜你喜欢
    • 2011-01-15
    • 2018-11-25
    • 2011-07-22
    • 2013-06-14
    • 2013-03-12
    • 1970-01-01
    • 1970-01-01
    • 2011-01-17
    • 1970-01-01
    相关资源
    最近更新 更多