我有我自己的 UserControl
<local:MyUserControl MyProperty="{Binding myString}"/>
而且我对此有约束力myString
。现在我想在我的电脑中使用它UserControl
。我已经DependencyProperty
在我的定义UserControl
:
public string MyProperty
{
get { return (string)GetValue(MyPropertyProperty); }
set
{
Debug.WriteLine(value);//writes nothing, null
SetValue(MyPropertyProperty, value);
}
}
public static readonly DependencyProperty MyPropertyProperty =
DependencyProperty.Register("MyProperty", typeof(string), typeof(MyUserControl), new PropertyMetadata(null));
我究竟做错了什么?我想用这个字符串做一些事情。但是它始终为空。
该Debug.WriteLine(value);
不是因为价值是什么都不写null
。不能保证运行依赖项属性的getter和setter,而在使用时{Binding}
,不会调用属性的setter。您可以在设置器中添加一个断点进行测试。
请注意“自定义依赖项属性”中的以下注意事项:
在除特殊情况外的所有情况下,包装器实现都应仅执行GetValue和SetValue操作。否则,通过XAML设置属性与通过代码设置属性时,您将获得不同的行为。为了提高效率,XAML解析器在设置依赖项属性时会绕过包装器。只要有可能,它将使用依赖项属性的注册表。
您可以在原始调用中添加一个更改了属性的处理程序,而无需在属性的设置程序中做出反应,并且可以DependencyProperty.Register
在此处理程序中对新值进行操作。例如:
public string MyProperty
{
get { return (string)GetValue(MyPropertyProperty); }
set
{
SetValue(MyPropertyProperty, value);
}
}
public static readonly DependencyProperty MyPropertyProperty =
DependencyProperty.Register("MyProperty", typeof(string), typeof(MyUserControl), new PropertyMetadata(null, OnPropertyChanged));
private static void OnPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if ((string)e.NewValue != (string)e.OldValue)
{
Debug.WriteLine(e.NewValue);
}
}
如果你想使用绑定串在你的UserControl
,你可以使用MyProperty
的UserControl
。例如:
在您的UserControl
:
<UserControl Name="root" ...>
<StackPanel>
<TextBlock Text="{Binding MyProperty, ElementName=root}" />
</StackPanel>
</UserControl>
然后,当您使用时<local:MyUserControl MyProperty="{Binding myString}"/>
,UserControl
将显示的值myString
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句