C# 更改更新控件上的WPF依赖项属性
我当前正在尝试获取一个视图,以便在依赖项值更改时进行更新 我已经将代码从视图复制到它的父视图中,并且没有使用依赖项,因此工作正常。我相信我的问题在于如何创建DependencyPropertyC# 更改更新控件上的WPF依赖项属性,c#,wpf,dependencies,dependency-properties,C#,Wpf,Dependencies,Dependency Properties,我当前正在尝试获取一个视图,以便在依赖项值更改时进行更新 我已经将代码从视图复制到它的父视图中,并且没有使用依赖项,因此工作正常。我相信我的问题在于如何创建DependencyProperty public partial class CULabelConfigControl : UserControl { private CreditUnion CU { get; set; } public static readonly DependencyProperty CUProp
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}}"/>
应该是这样的:
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}}"/>
由于多种原因,该声明遭到破坏。请先读。除了这里解释的内容之外,您不需要为依赖项属性实现INotifyPropertyChanged。他们提供自己的更改通知机制。谢谢,我将修剪INotifyPropertyChanged,我当时正在尝试任何方法使其工作。由于多种原因,该声明被破坏。请先读。除了这里解释的内容之外,您不需要为依赖项属性实现INotifyPropertyChanged。他们提供自己的更改通知机制。谢谢,我将修剪INotifyPropertyChanged,我当时正在尝试使其工作。很抱歉,我更新了代码,因为类型不匹配。”CurrentReading“”应该是“CU”。很抱歉,这解决了运行时错误,但由于某些原因,在依赖项对象更改时不会触发视图更改。您应该在CULabelConfigControl的XAML中的某个位置具有与CU属性的RelativeSource绑定。查看编辑。抱歉,我不是有意将我的XAML添加到您的答案中。我试着把它添加到我的问题中作为参考,效果非常好。我确实需要家属财产变更。谢谢您的帮助。很抱歉,我更新了代码,因为类型不匹配。”CurrentReading“”应该是“CU”。很抱歉,这解决了运行时错误,但由于某些原因,在依赖项对象更改时不会触发视图更改。您应该在CULabelConfigControl的XAML中的某个位置具有与CU属性的RelativeSource绑定。查看编辑。抱歉,我不是有意将我的XAML添加到您的答案中。我试着把它添加到我的问题中作为参考,效果非常好。我确实需要家属财产变更。谢谢你的帮助。