我有自己的UserControl
<local:MyUserControl MyProperty="{Binding myString}"/>
我正在将 myString
绑定(bind)到它。现在我想在我的 UserControl
中使用它。我在我的 UserControl
中定义了 DependencyProperty
:
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
。使用 {Binding}
时,不保证依赖属性的 getter 和 setter 能够运行,您的属性(property)的设置者不会被调用。您可以在setter中添加断点来测试它。
请注意Custom dependency properties中的以下警告:
In all but exceptional circumstances, your wrapper implementations should perform only the GetValue and SetValue operations. Otherwise, you'll get different behavior when your property is set via XAML versus when it is set via code. For efficiency, the XAML parser bypasses wrappers when setting dependency properties; whenever possible, it uses the registry of dependency properties.
您可以在对DependencyProperty.Register
的原始调用中添加属性更改处理程序,而不是在属性的 setter 中使用react。在此处理程序中,您可以对新值进行操作。例如:
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
中使用绑定(bind)字符串,您可以使用MyProperty
UserControl
的。例如:
在您的 UserControl
中:
<UserControl Name="root" ...>
<StackPanel>
<TextBlock Text="{Binding MyProperty, ElementName=root}" />
</StackPanel>
</UserControl>
然后当你使用<local:MyUserControl MyProperty="{Binding myString}"/>
时,你的UserControl
将显示 myString
的值.
关于c# - 如何在 UserControl 中使用绑定(bind)的 XAML 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34033198/