我目前正在尝试在依赖项值更改时获取更新视图。
我已将视图中的代码复制到其父级中,并且未使用该依赖项,并且工作正常。我相信我的问题在于我如何创建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."
正确方向的任何一点都会有所帮助。如果我需要分享任何其他细节,请告诉我。
答案 0 :(得分:3)
它应该是这样的:
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
}