[英]WPF Dependency Property On Change Update Control
我目前正在尝试获取一个依赖关系值更改时更新的视图。
我已经将视图中的代码复制到它的父级中,并且没有使用依赖项,并且运行良好。 我相信我的问题在于如何创建DependencyProperty。
public partial class CULabelConfigControl : UserControl {
private CreditUnion CU { get; set; }
public static readonly DependencyProperty CUProperty = DependencyProperty.Register(
"CU",
typeof(CreditUnion),
typeof(CULabelConfigControl),
new FrameworkPropertyMetadata(null)
);
我目前在运行时收到错误消息:
"A 'Binding' cannot be set on the 'CU' property of type 'CULabelConfigControl'.
A 'Binding' can only be set on a DependencyProperty of a DependencyObject."
朝正确方向的任何观点都会有所帮助。 并告诉我是否需要分享其他详细信息。
它看起来应该像这样:
public partial class CULabelConfigControl : UserControl
{
public static readonly DependencyProperty CUProperty =
DependencyProperty.Register(
nameof(CU),
typeof(CreditUnion),
typeof(CULabelConfigControl));
public CreditUnion CU
{
get { return (CreditUnion)GetValue(CUProperty); }
set { SetValue(CUProperty, value); }
}
}
在UserControl的XAML中,您可以通过将UserControl指定为RelativeSource来绑定到此属性,例如
<Label Content="{Binding CU, RelativeSource={RelativeSource AncestorType=UserControl}}"/>
如果每当属性值更改时都需要在UserControl类中得到通知,则应注册一个PropertyChangedCallback:
public static readonly DependencyProperty CUProperty =
DependencyProperty.Register(
nameof(CU),
typeof(CreditUnion),
typeof(CULabelConfigControl),
new PropertyMetadata(CUPropertyChanged));
private static void CUPropertyChanged(
DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
var control = (CULabelConfigControl)obj;
// react on value change here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.