【问题标题】:Is there a way to specify a custom dependency property's default binding mode and update trigger?有没有办法指定自定义依赖属性的默认绑定模式和更新触发器?
【发布时间】:2011-02-09 11:23:49
【问题描述】:

我想这样做,默认情况下,当我绑定到我的依赖属性之一时,绑定模式是双向的,并且 update-trigger 是属性更改。有没有办法做到这一点?

这是我的依赖属性之一的示例:

public static readonly DependencyProperty BindableSelectionLengthProperty =
        DependencyProperty.Register(
        "BindableSelectionLength",
        typeof(int),
        typeof(ModdedTextBox),
        new PropertyMetadata(OnBindableSelectionLengthChanged));

【问题讨论】:

    标签: c# data-binding dependency-properties


    【解决方案1】:

    在依赖属性声明中,它看起来像这样:

    public static readonly DependencyProperty IsExpandedProperty = 
            DependencyProperty.Register("IsExpanded", typeof(bool), typeof(Dock), 
            new FrameworkPropertyMetadata(true,
                FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
                OnIsExpandedChanged));
    
    public bool IsExpanded
    {
        get { return (bool)GetValue(IsExpandedProperty); }
        set { SetValue(IsExpandedProperty, value); }
    }
    

    【讨论】:

      【解决方案2】:

      注册属性时,初始化您的元数据:

      new FrameworkPropertyMetadata
      {
          BindsTwoWayByDefault = true,
          DefaultUpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
      }
      

      【讨论】:

      • 我可以通过将其添加到我的示例 dp 来设置 BindsTwoWayByDefault:new FrameworkPropertyMetadata(0, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnBindableSelectionStartChanged)。但是,我仍然无法将 UpdateSourceTrigger 设置为 PropertyChanged。
      • 我修改了我的答案,以展示如何使用对象初始化程序来做到这一点。使用它而不是构造函数。
      • @DiegoMijelshon 有没有办法只允许单向绑定模式?
      • 非常酷,我只是在寻找手动实现双向模式。
      • 猜想值得注意的是,除了TwoWay 之外,无法将默认值更改为任何其他模式。所以OneTimeOneWayToSource 被排除在外。至少我没有找到办法。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-30
      • 1970-01-01
      • 1970-01-01
      • 2010-12-26
      • 1970-01-01
      • 2013-10-16
      相关资源
      最近更新 更多