问题描述
我的用户控件上下文菜单可见性无法绑定依赖项属性。知道吗?
My user control context menu visibility can't bind a dependency property. Any idea?
这是我的WPF代码
<UserControl.ContextMenu>
<ContextMenu Visibility="{Binding ElementName=wellControl, Path=IsInCompactMode, Converter={StaticResource BooleanToVisibilityConverter}}">
<MenuItem Command="local:GCommands.Edit" />
<MenuItem Command="local:GCommands.Delete" />
<MenuItem Command="local:GCommands.ExportFcsFiles" />
<MenuItem Command="local:GCommands.BatchExportStatistics" />
<Separator/>
<MenuItem Command="local:GCommands.SaveAs" Header="Save As..." />
</ContextMenu>
</UserControl.ContextMenu>
如果我设置Visibility = Hidden,它将对我有用。
像这样:
If I set Visibility="Hidden" it will work for me.like this:
<ContextMenu Visibility="Hidden"/>
如果使用此功能将不起作用
If use this it won't work
<ContextMenu Visibility="{Binding ElementName=wellControl, Path=IsInCompactMode, Converter={StaticResource BooleanToVisibilityConverter}}">
我很确定Visibility = {Binding ElementName = wellControl,Path = IsInCompactMode,Converter = { 没有问题,因为它对其他人有用。
I'm pretty sure Visibility="{Binding ElementName=wellControl, Path=IsInCompactMode, Converter={StaticResource BooleanToVisibilityConverter}}" has not problem, cuz it works for others.
这是我的依赖项属性
public bool IsInCompactMode
{
get {return (bool)GetValue(IsInCompactModeProperty); }
set {SetValue(IsInCompactModeProperty, value); }
}
public static readonly DependencyProperty IsInCompactModeProperty =
DependencyProperty.Register("IsInCompactMode", typeof(bool), typeof(WellControl), new PropertyMetadata(false));
我尝试过这种方式,看来还是不行,这真的很奇怪!!!
I tried this way, it seems it still doesn't work, this is really weird!!!
<ContextMenu x:Name="menu" IsOpen="{Binding ElementName=wellControl, Path=IsInCompactMode}">
我真的很困惑,这是怎么回事? Binding ElementName = wellControl,Path = IsInCompactMode适用于用户控件的其他部分,只是不适用于怪异的上下文菜单?
I'm really confuse about it, what's wrong? "Binding ElementName=wellControl, Path=IsInCompactMode" works for other part of the user control, just doesn't work for the weird context menu? it doesn't make sence
推荐答案
1> ContextMenu,弹出窗口,DataGridColumns都不是可视树的一部分。因此,使用 ElementName
或 RelativeSource
的绑定将无法像这样工作。
1> ContextMenu, Popups, DataGridColumns are not part of visual tree. So the binding using ElementName
or RelativeSource
wont work just like that.
2> 当您不想在特定情况下显示上下文菜单时,请使用触发器从视觉本身取消设置上下文菜单。
<TextBlock Text="ContextMenu is not shown when DataContext.IsShow is false"}">
<TextBlock.Style>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="ContextMenu"
Value="{StaticResource TextBlockContextMenu}" />
<Style.Triggers>
<DataTrigger Binding="{Binding IsShow}"
Value="False">
<Setter Property="ContextMenu"
Value="{x:Null}" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
3>要将这些项目附加到可视化树上,以便进行绑定,我们使用proxy元素方法...
3> To attach these items to the visual tree, so that binding works, we use the proxy element method...
我更喜欢第二步。
这篇关于WPF UserControl上下文菜单可见性绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!