繁体   English   中英

绑定到UserControl的依赖属性

[英]Binding to a Dependency Property of UserControl

我有一个WPF用户控件,它有一个名为IsMultiSelect的DependencyProperty。 我想在UserControl xaml中隐藏一个Button。

<Button Visibility="{Binding IsMultiSelect, Converter=....}" />

此用户控件具有分配给DataContext的ViewModel。 由于视图模型中不存在属性,上面的语法给出了绑定错误。

我该如何解决这个错误?

您可以在绑定中以不同方式定位UserControl

一种解决方案是通过设置这样的RelativeSource来找到它:

<Button Visibility="{Binding IsMultiSelect, 
    RelativeSource={RelativeSource AncestorType={x:Type UserControl}},
    Converter=....}" />

而不是从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); }
}

您也可以将转换器逻辑放在OnIsMultiSelectPropertyChanged中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM