且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

WPF UserControl 上下文菜单可见性绑定

更新时间:2022-06-22 08:26:01

1> ContextMenu、Popups、DataGridColumns 不是可视化树的一部分.所以使用 ElementNameRelativeSource 的绑定不会像那样工作.

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> 要将这些项目附加到可视化树,以便绑定起作用,我们使用代理元素方法...

3> To attach these items to the visual tree, so that binding works, we use the proxy element method...

绑定数据网格列可见性MVVM

我更喜欢第二步.