3

我有一个使用 ItemsSource 绑定到集合的上下文菜单:

<Button Content="Submit">
<Button.ContextMenu>
    <ContextMenu Name="SubmitButtonContextMenu" ItemsSource="{Binding MyDataSource}">
        <ContextMenu.ItemContainerStyle>
            <Style TargetType="{x:Type MenuItem}">
                <!-- Setters -->
            </Style>
        </ContextMenu.ItemContainerStyle>
    </ContextMenu>
</Button.ContextMenu>
</Button>

它目前会像这样显示:菜单项

基本上,我想添加两个静态项:另一个永远不会更改的 MenuItem,以及一个用于分隔静态内容和动态内容的分隔符。我可以用这些数据填充我的收藏,但我觉得应该有一个更优雅的解决方案。我也希望避免使用子上下文菜单。

编辑:这是我最终实施的:

<Window ...>
<Window.Resources>
    <s:SubmitItemStyleSelector x:Key="SubmitItemStyleSelector">
        <s:SubmitItemStyleSelector.SubmitButtonStyle>
            <Style TargetType="MenuItem">
                <!--Setters-->
            </Style>
        </s:SubmitItemStyleSelector.SubmitButtonStyle>
    </s:SubmitItemStyleSelector>
    <CollectionViewSource x:Key="MyDataViewSource" Source="{Binding MyDataSource}"/>
</Window.Resources>
...
<Button Content="Submit">
    <Button.ContextMenu>
        <ContextMenu ItemContainerStyleSelector="{Binding Source={StaticResource SubmitItemStyleSelector}}">
            <ContextMenu.ItemsSource>
                <CompositeCollection>
                    <MenuItem Header="No Change"/>
                    <Separator/>
                    <CollectionContainer Collection="{Binding Source={StaticResource MyDataViewSource}}"/>
                </CompositeCollection>
            </ContextMenu.ItemsSource>
        </ContextMenu>
    </Button.ContextMenu>
</Button>

然后我的 SubmitItemStyleSelector 从 MyDataSource 中找到我想要的类型,以便对这些项目进行额外的样式设置。

4

1 回答 1

6

您应该使用CompositeCollection( msdn ):

<Window ..
       >
    <Window.Resources>
        <CollectionViewSource x:Key="MyDynamicDataSource" Source="{Binding Path=MyDataSource}" />
    ...
    </Window.Resources>
    ...
    <Button Content="Submit" >
        <Button.ContextMenu>
            <ContextMenu Name="SubmitButtonContextMenu">
                <ContextMenu.ItemsSource>
                    <CompositeCollection>
                        <MenuItem Header="First static item" />
                        <MenuItem Header="Second static item" />
                        <Separator />
                        <CollectionContainer Collection="{Binding Source={StaticResource MyDynamicDataSource}}" />
                    </CompositeCollection>
                </ContextMenu.ItemsSource>
            </ContextMenu>
        </Button.ContextMenu>
    </Button>
    ...
</Window>
于 2013-10-25T20:12:02.257 回答