WPF UserControl Context Menu Visibility Binding

左心房为你撑大大i 提交于 2019-12-01 06:38:48
WPF-it

1> ContextMenu, Popups, DataGridColumns are not part of visual tree. So the binding using ElementName or RelativeSource wont work just like that.

2> When you want the context menu to not display under particular situation use the triggers to unset the context menu from the visual itself.

      <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> To attach these items to the visual tree, so that binding works, we use the proxy element method...

Bind datagrid column visibility MVVM

I prefer second step.

If you are trying to show/hide a context menu you should use the IsOpen property of the ContextMenu, rather than the Visibility property.

FAREH

You should add the Update Trigger : "UpdateSourceTrigger=PropertyChanged"

<DataGrid.ContextMenu >
    <ContextMenu Visibility="{Binding IsSelectionEnabled, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged,Converter={StaticResource BooleanToVisibilityConverter}}" >
        <ContextMenu.Items>
            <MenuItem Header="Create Layer" Command="{Binding DefineLayerName }" />
        </ContextMenu.Items>
    </ContextMenu>
</DataGrid.ContextMenu>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!