简体   繁体   English

MenuItem可见性绑定的ContextMenu

[英]ContextMenu of MenuItem visibility binding

I need to create a context menu for a menu item. 我需要为菜单项创建一个上下文菜单。 Visibility of the context menu is binded to the ViewModel. 上下文菜单的可见性已绑定到ViewModel。

When the property change to true, using MVVM Light, the context menu appears in the UI even if there is no right click on the menu item. 当属性更改为true时,使用MVVM Light,即使没有右键单击菜单项,上下文菜单也会出现在UI中。 What can I do to hide the context menu when the value is false, and alllow it to be visible only on right click ? 如果该值为false,我该怎么做才能隐藏上下文菜单,并使其仅在右键单击时可见?

private Boolean _IsEditable;
public Boolean IsEditable
{
    get { return _IsEditable; }
    set
    {
        if (_IsEditable == value) return;
        _IsEditable = value;
        RaisePropertyChanged("IsEditable");
    }
}

<Menu DockPanel.Dock="Top">
   <MenuItem Header="{Binding Menu.Business}" Visibility="{Binding allowUI, Converter={StaticResource BoolToVisConverter} }">
      <MenuItem.ContextMenu>
         <ContextMenu Visibility="{Binding Menu.IsEditable, Converter={StaticResource BoolToVisConverter} }">
            <MenuItem>
               <MenuItem.Header>
                  <TextBox Text="{Binding Menu.Business, UpdateSourceTrigger=PropertyChanged}" LostFocus="end_change_UI" />
               </MenuItem.Header>
            </MenuItem>

         </ContextMenu>
      </MenuItem.ContextMenu>
   </MenuItem>
</Menu>

You could apply a Style to the MenuItem that only sets the ContextMenu property when the IsEditable source property is set to true : 您可以将Style应用于仅在IsEditable源属性设置为true时设置ContextMenu属性的MenuItem

<Menu DockPanel.Dock="Top">
    <MenuItem Header="{Binding Menu.Business}" Visibility="{Binding allowUI, Converter={StaticResource BoolToVisConverter} }">
        <MenuItem.Style>
            <Style TargetType="MenuItem" BasedOn="{StaticResource {x:Type MenuItem}}">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Menu.IsEditable}" Value="True">
                        <Setter Property="ContextMenu">
                            <Setter.Value>
                                <ContextMenu>
                                    <MenuItem>
                                        <MenuItem.Header>
                                            <TextBox Text="{Binding Menu.Business, UpdateSourceTrigger=PropertyChanged}" LostFocus="end_change_UI" />
                                        </MenuItem.Header>
                                    </MenuItem>
                                </ContextMenu>
                            </Setter.Value>
                        </Setter>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </MenuItem.Style>
    </MenuItem>
</Menu>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM