动态隐藏菜单项 [英] Dynamically hiding menu items

查看:98
本文介绍了动态隐藏菜单项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用xaml构建的菜单,并且MenuItem的属性ItemTemplate设置为以下模板:

I have a menu built with xaml, and the MenuItem has the property ItemTemplate set to the following template:

<HierarchicalDataTemplate x:Key="MenuItemTemplate" DataType="{x:Type mainMenu:MenuItem}" ItemsSource="{Binding ChildMenuItems}">
     <MenuItem Command="{Binding Command}" CommandParameter="{Binding CommandParameter}" Header="{Binding Path=Header}" Visibility="{Binding Visible, Converter={converter:BooleanToVisibilityConverter}}" />
</HierarchicalDataTemplate>

当我将可见"属性的值更改为false以隐藏子菜单时,结果是这样的:

When I change the value of the property Visible to false with the intention of hiding the sub-menu what I have as a result is this:

子菜单是隐藏的,但它们仍需要一些空间.如何更改此设置以适应菜单中剩余的项目数?

The sub-menus are hidden but they still take some space. How can I change that to adapt to the number of items left in the menu?

这是转换器的代码:

public class BooleanToVisibilityConverter : MarkupExtension, IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return (bool) value ? Visibility.Visible : Visibility.Collapsed;
    }
}

推荐答案

您不应使用HierarchicalDataTemplate来定义您的孩子MenuItem.而是尝试使用MenuItem.ItemsSource属性:

You shouldn't be using a HierarchicalDataTemplate to define your child MenuItems. Instead, try using the MenuItem.ItemsSource property:

<DataTemplate x:Key="MenuItemTemplate" DataType="{x:Type mainMenu:MenuItem}">
    <MenuItem Command="{Binding Command}" CommandParameter="{Binding CommandParameter}"
        Header="{Binding Path=Header}" Visibility="{Binding Visible, Converter={
        converter:BooleanToVisibilityConverter}}" 
        ItemsSource="{Binding ChildMenuItems}" />
</DataTemplate>


更新>>>


UPDATE >>>

是的,很抱歉,您需要在设置为MenuItem.ItemContainerStyleStyle中设置子级MenuItem属性.与其在此进行解释,不如将其引导至

Yeah sorry, you need to set the child MenuItem properties in a Style set as the MenuItem.ItemContainerStyle. Rather than explain it all here, I prefer to direct you to the Binding menus using HeirarchicalDataTemplates page from Lester's WPF\SL Blog on MSDN, which explains how to do it well.

此外,如果要进行数据绑定MenuItem,则最好从数据绑定集合中删除相关项,而不必尝试设置Visibility.用户界面看起来一样,但是会简单得多.尽可能最好在WPF中操纵数据元素,而不是UI元素.

Also, if you're going to data bind the MenuItems, then you might as well remove the relevant items from the data bound collection instead of trying to set the Visibility. The UI will look the same, but it will be much simpler. It's always best to manipulate the data elements in WPF when you can, rather than the UI elements.

这篇关于动态隐藏菜单项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆