【问题标题】:Binding to a Dependency Property of UserControl绑定到 UserControl 的依赖属性
【发布时间】:2013-05-02 18:19:09
【问题描述】:

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

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

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

如何解决此错误?

【问题讨论】:

    标签: wpf


    【解决方案1】:

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

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

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

    【讨论】:

    • 这就是我要找的。这很完美。谢谢。使用 ElementName 也有效。
    【解决方案2】:

    依赖属性的属性更改处理程序应该更改按钮的可见性,而不是从 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 中。

    【讨论】:

      猜你喜欢
      • 2023-04-07
      • 1970-01-01
      • 2011-07-29
      • 2017-12-24
      • 2014-08-31
      • 2017-12-18
      • 1970-01-01
      • 1970-01-01
      • 2014-04-10
      相关资源
      最近更新 更多