Sar*_*hal 0 c# wpf dependencies dependency-properties
我目前正在尝试在依赖项值更改时更新视图。
我已将代码从视图复制到其父级中,并且没有使用依赖项,并且工作正常。我相信我的问题在于如何创建 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)
);
Run Code Online (Sandbox Code Playgroud)
我目前在运行时收到错误:
"A 'Binding' cannot be set on the 'CU' property of type 'CULabelConfigControl'.
A 'Binding' can only be set on a DependencyProperty of a DependencyObject."
Run Code Online (Sandbox Code Playgroud)
任何方向正确的点都会有所帮助。如果我需要分享任何其他细节,请告诉我。
它应该看起来像这样:
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); }
}
}
Run Code Online (Sandbox Code Playgroud)
在 UserControl 的 XAML 中,您可以通过将 UserControl 指定为relativesource 来绑定到此属性,例如
<Label Content="{Binding CU, RelativeSource={RelativeSource AncestorType=UserControl}}"/>
Run Code Online (Sandbox Code Playgroud)
如果您需要在属性值更改时在 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
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3130 次 |
最近记录: |