[英]Binding to a Dependency Property of UserControl
I have a WPF user control that has a DependencyProperty called IsMultiSelect. 我有一个WPF用户控件,它有一个名为IsMultiSelect的DependencyProperty。 I want to show hide a Button in the UserControl xaml.
我想在UserControl xaml中隐藏一个Button。
<Button Visibility="{Binding IsMultiSelect, Converter=....}" />
This user control has a ViewModel assigned to the DataContext. 此用户控件具有分配给DataContext的ViewModel。 The above syntax gives me a binding error due to the property not existing in the view model.
由于视图模型中不存在属性,上面的语法给出了绑定错误。
How can I fix this error? 我该如何解决这个错误?
You can target the UserControl
in different ways in the binding. 您可以在绑定中以不同方式定位
UserControl
。
One solution would be to find it by setting a RelativeSource
like this: 一种解决方案是通过设置这样的
RelativeSource
来找到它:
<Button Visibility="{Binding IsMultiSelect,
RelativeSource={RelativeSource AncestorType={x:Type UserControl}},
Converter=....}" />
Instead of binding to the property from xaml, the property changed handler for the dependency property should change the button's visibility. 而不是从xaml绑定到属性,属性更改依赖项属性的处理程序应该更改按钮的可见性。
public static readonly DependencyProperty IsMultiSelectProperty = DependencyProperty.Register("IsMultiSelect", typeof(bool), typeof(MyUserControl), new PropertyMetadata(false, OnIsMultiSelectPropertyChanged));
private static void OnIsMultiSelectPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
(sender as MyUserControl).OnIsMultiSelectPropertyChanged(e);
}
private void OnIsMultiSelectPropertyChanged(DependencyPropertyChangedEventArgs e)
{
MyButton.Visibility = (bool)e.NewValue ? Visibility.Visible : Visibility.Collapsed;
}
public bool IsMultiSelect
{
get { return (bool)GetValue(IsMultiSelectProperty); }
set { SetValue(IsMultiSelectProperty, value); }
}
And you can put the converter logic inside OnIsMultiSelectPropertyChanged as well. 您也可以将转换器逻辑放在OnIsMultiSelectPropertyChanged中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.