gpt4 book ai didi

c# - 自定义控件上的 DependencyProperty 没有绑定(bind)?

转载 作者:太空宇宙 更新时间:2023-11-03 10:41:35 25 4
gpt4 key购买 nike

我有一个带有标签的自定义控件。此控件具有如下属性 Label:

public string Label
{
get { return (string)GetValue(LabelProperty); }
set
{
label.Text = value;
SetValue(LabelProperty, value);
}
}

public static DependencyProperty LabelProperty = DependencyProperty.Register("Label", typeof(string), typeof(SuperButton), new PropertyMetadata(null));

请注意,带有小 l 的标签是一个内部文本 block 。 SuperButton 是控件的名称。

然后我有这个简单的对象:

class Student  : INotifyPropertyChanged
{
public string _name;
public string Name
{
get { return _name; }
set { _name = value; OnPropertyChanged( new PropertyChangedEventArgs("Name")); }
}

public event PropertyChangedEventHandler PropertyChanged;

public void OnPropertyChanged(PropertyChangedEventArgs e)
{
if (PropertyChanged != null)
{
PropertyChanged(this, e);
}
}
}

然后我用这个 XAML 绑定(bind):

<UIFragments:SuperButton Margin="531,354,555,367" Label="{Binding Name}"></UIFragments:SuperButton>

然后我将其与按钮实例放在同一页面中

    Student s = new Student { Name = "John Smith" };
DataContext = s;

我已经尝试将控件的数据上下文设置为其自身,但没有任何效果。将标签设置为字符串即可。

如果我使用数据绑定(bind),set{} block 永远不会触发...

最佳答案

XAML 不会调用您的 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 LabelProperty = DependencyProperty.Register(
"Label",
typeof(string),
typeof(SuperButton),
new PropertyMetadata(null, PropertyChangedCallback)
);

注意最后一行的PropertyChangedCallback!该方法实现如下:

private static void PropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs args)
{
SuperButton userControl = ((SuperButton)dependencyObject);
userControl.label.Text = (string) args.NewValue;
}

依赖属性的 getter 和 setter 现在可以简化为:

public string Label
{
get { return (string)GetValue(LabelProperty); }
set { SetValue(LabelProperty, value); }
}

现在每当 Label 属性发生变化时,例如通过在您的页面中绑定(bind)它,调用 PropertyChangedCallback 并将文本传递给您的实际标签!

关于c# - 自定义控件上的 DependencyProperty 没有绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25180485/

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