有两个上下文菜单。要打开所需的上下文菜单,请单击鼠标右键。如果IsData为true,则ContextMenu1将打开;如果IsData为false,则将打开ContextMenu2。该问题将在XAML中展开。
DataTemplate中有两个静态上下文菜单。一个上下文菜单如何使用它们? 此块完全设置模板上下文菜单。选择哪个,取决于条件。
<DataTemplate x:Key="ContextMenuControlTemplate">
<DataTemplate.Resources>
<ContextMenu x:Key="ContextMenuSet">
<MenuItem>
<MenuItem.Header>
<StackPanel Orientation="Horizontal">
<Image Width="15" Height="15" Source="{DynamicResource img_icon}"/>
<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text=" Add item" />
</StackPanel>
</MenuItem.Header>
<MenuItem.Icon>
<RadioButton IsChecked="True"/>
</MenuItem.Icon>
</MenuItem>
<MenuItem Header="Remove"></MenuItem>
</ContextMenu>
<ContextMenu x:Key="ContextMenuDel">
<MenuItem Header=" Del all"></MenuItem>
</ContextMenu>
</DataTemplate.Resources>
<ContextMenu x:Name="contextMenuForItems"/>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding Data.IsData}" Value="true">
<Setter TargetName="contextMenuForItems" Property="ContextMenu" Value="{StaticResource ContextMenuSet}" />
</DataTrigger>
<DataTrigger Binding="{Binding Data.IsData}" Value="false">
<Setter TargetName="contextMenuForItems" Property="ContextMenu" Value="{StaticResource ContextMenuDel}" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
这里的块试图使用我们建立的上下文菜单。这就是问题所在。
<DataTemplate>
<DockPanel>
<ContextMenu>
<DataTemplate>
<ContentControl Content="{Binding Data.IsData}"
ContentTemplate="{StaticResource ContextMenuControlTemplate}"
/>
</DataTemplate>
</ContextMenu>
</DockPanel>
</DataTemplate>
答案 0 :(得分:0)
我使用了解决方法。我做了一个复杂的菜单。并删除了一些缺少的MenuItem。请参阅关键字Visibility和booleanToVisibilityConverter。我的例子如下。
<DockPanel.ContextMenu>
<ContextMenu>
<MenuItem IsEnabled="False" Visibility="{Binding Data.IsData, Converter={StaticResource booleanToVisibilityConverter2}}">
<MenuItem.Header>
<StackPanel Orientation="Horizontal">
<Image Width="15" Height="15" Source="{DynamicResource img_icon}"/>
<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text=" Add item" />
</StackPanel>
</MenuItem.Header>
<MenuItem.Icon>
<RadioButton IsChecked="True"/>
</MenuItem.Icon>
</MenuItem>
<MenuItem Click="MenuItem_Click" Header="Remove" Visibility="{Binding Data.IsData, Converter={StaticResource booleanToVisibilityConverter2}}" />
<MenuItem Click="MenuItem_Click" Header="Del all" Visibility="{Binding Data.IsData, Converter={StaticResource booleanToVisibilityConverter2}, ConverterParameter=InvertCollapse}" />
</ContextMenu>
</DockPanel.ContextMenu>
booleanToVisibilityConverter2是BooleanToVisibilityConverter的包装器,它具有其他属性。