【问题标题】:Custom control style only applies to contextmenu when it appears for the 2nd time自定义控件样式仅在第二次出现时适用于上下文菜单
【发布时间】:2018-09-01 22:33:31
【问题描述】:

我正在尝试创建一个没有左侧图标栏的上下文菜单。

我这样做的方式是通过适用于我窗口中所有 ContextMenus 和 MenuItems 的自定义样式:

<Window.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            ...
            ...
            <ResourceDictionary>
                <Style TargetType="ContextMenu">
                    <Setter Property="ItemsPanel">
                        <Setter.Value>
                            <ItemsPanelTemplate>
                                <StackPanel Background="White"/>
                            </ItemsPanelTemplate>
                        </Setter.Value>
                    </Setter>
                    <Setter Property="ItemContainerStyle">
                        <Setter.Value>
                            <Style TargetType="MenuItem">
                                <Setter Property="Command" Value="{Binding RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"/>
                                <Setter Property="CommandParameter" Value="{Binding}"/>
                            </Style>
                        </Setter.Value>
                    </Setter>
                    <Setter Property="ItemTemplate">
                        <Setter.Value>
                            <DataTemplate>
                                <Grid Margin="-20,0,-40,0">
                                    <TextBlock Text="{Binding}"/>
                                </Grid>
                            </DataTemplate>
                        </Setter.Value>
                    </Setter>
                </Style>
            </ResourceDictionary>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Window.Resources>

然后我在窗口中的一个按钮上生成 ContextMenu:

                        <Button Content="Add"
                            Margin="5"
                            Width="90"
                            ContextMenuService.Placement="Bottom">
                        <Button.ContextMenu>
                            <ContextMenu ItemsSource="{Binding ModifierOptions}"/>
                        </Button.ContextMenu>
                    </Button>

问题是上下文菜单第一次出现时,缺少样式,所以还是有侧栏

如果之后我再次右键单击该按钮,则样式将正确应用并且不存在侧栏。 知道会发生什么吗?

【问题讨论】:

  • 我从您的示例中删除了 MergedDictionaries,并且效果很好。不知道为什么,但...

标签: wpf xaml resources styles contextmenu


【解决方案1】:

作为一种解决方法,您可以将样式移动到单独的 ResourceDictionary。它适用于我的情况。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多