【问题标题】:Binding to a usercontrol's DependencyProperty is not calling the setter绑定到用户控件的 DependencyProperty 不会调用 setter
【发布时间】:2014-08-26 08:25:54
【问题描述】:

我的页面 xaml:

<header:DefaultText x:Name="header" HeaderText="{Binding Resources.HeaderTitle}"/>

我的 DefaultText.cs DependencyProperty:

    public string HeaderText
    {
        get { return (string)GetValue(HeaderTextProperty); }
        set
        {   //This part is never called when binding, but it is with static text
            SetValue(HeaderTextProperty, value);
            SetText(value);
        }
    }

    public readonly DependencyProperty HeaderTextProperty = DependencyProperty.Register("HeaderText", typeof(string), typeof(DefaultText), new PropertyMetadata(string.Empty));

我的问题是,当我使用绑定设置 HeaderText 属性时,不会调用 setter,但是当我使用没有绑定的普通字符串时,会调用它。

我已经尝试过类似问题的答案,例如:WPF Binding to variable / DependencyProperty

【问题讨论】:

标签: c# xaml dependency-properties windows-phone-8.1


【解决方案1】:

XAML 绑定内部不会调用您的 Setter 方法,而是直接设置依赖项属性的值,正如 at MSDN 所指出的那样:

WPF XAML 处理器使用属性系统方法进行依赖 加载二进制 XAML 和处理属性时的属性 依赖属性。这有效地绕过了属性 包装纸。当你实现自定义依赖属性时,你必须 考虑到这种行为,并应避免将任何其他代码放入 您的属性包装器,而不是属性系统方法 GetValue 和 SetValue。

你需要做的是注册一个回调方法,只要依赖属性发生变化就会触发:

public static DependencyProperty HeaderTextProperty = DependencyProperty.Register(
    "HeaderText", 
    typeof(string), 
    typeof(DefaultText), 
    new PropertyMetadata(string.Empty, PropertyChangedCallback)
);

private static void PropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs args)
{
    // this is the method that is called whenever the dependency property's value has changed
}

【讨论】:

  • 感谢您的快速回复和解释,它似乎仍然无法正常工作,我是否还遗漏了其他内容?当我不使用绑定时会调用 PropertyChangedCallback,但在使用绑定时不会调用。
  • 也许您的依赖属性根本没有更新,尝试将{Binding ..., Mode=TwoWay} 添加到绑定以强制双向更新?
  • 我将其更改为HeaderText="{Binding Resources.HeaderTitle, Mode=TwoWay}",但它似乎仍然无法正常工作。当我在 TextBlock.Text 等普通控件而不是用户控件上使用绑定时,绑定确实有效。
  • 另一个想法:您能否检查Resources.HeaderTitle(或您要绑定的任何内容)在评估绑定时是否真的包含一些数据?如果绑定值等于依赖属性的默认值(在您的情况下为string.Empty),则不会触发回调。
  • 这就是问题所在,译者似乎漏掉了那个。非常感谢!
猜你喜欢
  • 2012-02-08
  • 2015-01-15
  • 2011-01-18
  • 1970-01-01
  • 1970-01-01
  • 2012-02-25
  • 1970-01-01
  • 2012-04-15
  • 2020-09-01
相关资源
最近更新 更多