2

我创建了以下菜单。现在我想在不同的窗口上使用相同的菜单布局,并考虑将下面的代码转移到 Generic.xaml 并只在需要时引用它。最好的方法是什么,以便实际使用尽可能短?

<MenuHeight="27"VerticalAlignment="Top" ItemsSource="{Binding Menu}">
    <Menu.ItemContainerStyle>
        <Style TargetType="MenuItem">
            <Setter Property="Command" Value="{Binding Execute}"/>
            <Setter Property="Icon" Value="{Binding Icon}" />
            <Setter Property="ToolTip" Value="{Binding ToolTip}"/>
        </Style>
    </Menu.ItemContainerStyle>
    <Menu.ItemTemplate>
        <HierarchicalDataTemplate ItemsSource="{Binding Children}" >
            <TextBlock Text="{Binding Header}" />
            <HierarchicalDataTemplate.ItemContainerStyle>
                <Style TargetType="MenuItem">
                    <Setter Property="Command" Value="{Binding Execute}"/>
                    <Setter Property="Icon" Value="{Binding Icon}" />
                    <Setter Property="ToolTip" Value="{Binding ToolTip}"/>
                </Style>
            </HierarchicalDataTemplate.ItemContainerStyle>
        </HierarchicalDataTemplate>
    </Menu.ItemTemplate>
</Menu>
4

1 回答 1

3

将其放在资源中,它将应用于范围内的每个菜单:

<Style x:Key="{x:Type Menu}" TargetType="Menu">
    <Setter Property="ItemContainerStyle">
        <Setter.Value>
            <Style TargetType="MenuItem">
                <Setter Property="Command" Value="{Binding Execute}"/>
                <Setter Property="Icon" Value="{Binding Icon}" />
                <Setter Property="ToolTip" Value="{Binding ToolTip}"/>
            </Style>
        </Setter.Value>
    </Setter>
    <Setter Property="ItemTemplate">
        <Setter.Value>
            <HierarchicalDataTemplate ItemsSource="{Binding Children}" >
                <TextBlock Text="{Binding Header}" />
                <HierarchicalDataTemplate.ItemContainerStyle>
                    <Style TargetType="MenuItem">
                        <Setter Property="Command" Value="{Binding Execute}"/>
                        <Setter Property="Icon" Value="{Binding Icon}" />
                        <Setter Property="ToolTip" Value="{Binding ToolTip}"/>
                    </Style>
                </HierarchicalDataTemplate.ItemContainerStyle>
            </HierarchicalDataTemplate>
        </Setter.Value>
    </Setter>
</Style>
于 2013-06-12T11:39:40.060 回答