【发布时间】: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,然后通过祖先链?
-
<ContextMenu IsEnabled={Binding UseContextMenu, RelativeSource={RelativeSource AncestorType=UserControl}}" /> -
找不到,已用我的尝试更新了问题
-
对,ContextMenus 不在可视化树中;我的错。我可以用binding proxy 做到这一点(这个答案说明了用一个做其他事情)。然而,禁用上下文菜单是有问题的:它仍然打开,但所有项目都被禁用——而且它没有正确关闭。给你的 DataGrid 一个 Style 可能会更好,当该属性为 true 时,它会为其分配上下文菜单。
-
啊,好主意。我去看看这个代理,谢谢。
标签: c# wpf xaml user-controls dependency-properties