【问题标题】:Binding to a Dependency Property inside UserControl XAML绑定到 UserControl XAML 中的依赖属性
【发布时间】:2017-12-18 15:33:49
【问题描述】:

我想重用一个控件,但其中一种情况需要上下文菜单,而其他情况则不需要。这是我的尝试。

public partial class RP8Grid : UserControl {

    public bool UseContextMenu {
        get { return (bool)GetValue(UseContextMenuProperty); }
        set { SetValue(UseContextMenuProperty, value); }
    }

    // Using a DependencyProperty as the backing store for UseContextMenu.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty UseContextMenuProperty =
        DependencyProperty.Register("UseContextMenu", typeof(bool), typeof(RP8Grid), new PropertyMetadata(false));

        public RP8Grid() {
            InitializeComponent();
        }
    }

并在 XAML 中使用该属性:

<ctls:RP8Grid UseContextMenu="False"/>

现在我无法解决的部分,如何访问 UserControl 中的 UseContextMenu? 我尝试了以下方法:

<DataGrid>
  <DataGrid.ContextMenu>
    <ContextMenu IsEnabled="{Binding UseContextMenu,RelativeSource={RelativeSource AncestorType=UserControl, Mode=FindAncestor}}">
  </DataGrid.ContextMenu>
</DataGrid>

结果:

找不到与引用“RelativeSource”绑定的源 FindAncestor, AncestorType='System.Windows.Controls.UserControl', AncestorLevel='1'

【问题讨论】:

  • 你说得对,我想我打的是 propa 而不是 propdp。我的第一个实现。 RelativeSource,然后通过祖先链?
  • &lt;ContextMenu IsEnabled={Binding UseContextMenu, RelativeSource={RelativeSource AncestorType=UserControl}}" /&gt;
  • 找不到,已用我的尝试更新了问题
  • 对,ContextMenus 不在可视化树中;我的错。我可以用binding proxy 做到这一点(这个答案说明了用一个做其他事情)。然而,禁用上下文菜单是有问题的:它仍然打开,但所有项目都被禁用——而且它没有正确关闭。给你的 DataGrid 一个 Style 可能会更好,当该属性为 true 时,它​​会为其分配上下文菜单。
  • 啊,好主意。我去看看这个代理,谢谢。

标签: c# wpf xaml user-controls dependency-properties


【解决方案1】:

如果您想要的只是有时摆脱ContextMenu,这将起作用:

<DataGrid 
    >
    <DataGrid.Style>
        <Style TargetType="DataGrid" BasedOn="{StaticResource {x:Type DataGrid}}">
            <Style.Triggers>
                <DataTrigger 
                    Binding="{Binding UseContextMenu, RelativeSource={RelativeSource AncestorType=UserControl}}"
                    Value="True"
                    >
                    <Setter Property="ContextMenu">
                        <Setter.Value>
                            <ContextMenu 
                                >
                                <MenuItem Header="Test Item" />
                                <MenuItem Header="Test Item" />
                                <MenuItem Header="Test Item" />
                                <MenuItem Header="Test Item" />
                            </ContextMenu>
                        </Setter.Value>
                    </Setter>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGrid.Style>
</DataGrid>

【讨论】:

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