MenuItem可见性绑定的ContextMenu

时间:2017-03-16 20:57:29

标签: c# wpf mvvm-light

我需要为菜单项创建一个上下文菜单。上下文菜单的可见性绑定到ViewModel。

当属性更改为true时,使用MVVM Light,即使没有右键单击菜单项,也会在UI中显示上下文菜单。当值为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>

1 个答案:

答案 0 :(得分:0)

您可以将Style应用于仅在MenuItem源属性设置为ContextMenu时设置IsEditable属性的true

<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>