gpt4 book ai didi

c# - 绑定(bind)到用户控件的 DependencyProperty 不调用 setter

转载 作者:太空宇宙 更新时间:2023-11-03 20:03:39 27 4
gpt4 key购买 nike

我的页面 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));

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

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

最佳答案

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

The WPF XAML processor uses property system methods for dependency properties when loading binary XAML and processing attributes that are dependency properties. This effectively bypasses the property wrappers. When you implement custom dependency properties, you must account for this behavior and should avoid placing any other code in your property wrapper other than the property system methods GetValue and 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
}

关于c# - 绑定(bind)到用户控件的 DependencyProperty 不调用 setter ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25501228/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com