哪个WPF控件允许在每个项目上列出项目和上下文菜单?直到现在,我一直在使用ListBox,但好像没有简单的方法将上下文菜单添加到它的项目中。相反,我正在将ListBox更改为另一个允许上下文菜单的控件。WPF列表和上下文菜单
我现在使用的唯一ListBox属性/方法是“SelectedIndex”和“SelectedItem”。只要建议的控制支持这个或有另一个替代品,我应该没问题。
哪个WPF控件允许在每个项目上列出项目和上下文菜单?直到现在,我一直在使用ListBox,但好像没有简单的方法将上下文菜单添加到它的项目中。相反,我正在将ListBox更改为另一个允许上下文菜单的控件。WPF列表和上下文菜单
我现在使用的唯一ListBox属性/方法是“SelectedIndex”和“SelectedItem”。只要建议的控制支持这个或有另一个替代品,我应该没问题。
添加ContextMenu
到ListBoxItem
使用ItemContainerStyle
<ListBox ItemsSource="{Binding ...}">
<ListBox.Resources>
<ContextMenu x:Key="listBoxItemContextMenu">
<MenuItem Header="{Binding YourProperty}" />
</ContextMenu>
</ListBox.Resources>
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="ContextMenu"
Value="{StaticResource listBoxItemContextMenu}"/>
</Style>
</ListBox.ItemContainerStyle>
<!--...-->
</ListBox>
这个例子不使用任何约束力或类似的DataTemplates你可能会通常在实际应用中看到,但希望它有助于
<ListBox>
<ListBox.Items>
<ListBoxItem Content="Item A">
<ListBoxItem.ContextMenu>
<ContextMenu>Delete A</ContextMenu>
</ListBoxItem.ContextMenu>
</ListBoxItem>
<ListBoxItem Content="Item B">
<ListBoxItem.ContextMenu>
<ContextMenu>Delete B</ContextMenu>
</ListBoxItem.ContextMenu>
</ListBoxItem>
<ListBoxItem Content="Item C">
<ListBoxItem.ContextMenu>
<ContextMenu>Delete A</ContextMenu>
</ListBoxItem.ContextMenu>
</ListBoxItem>
</ListBox.Items>
</ListBox>
所以在我的应用程序中,我不得不以编程方式将这些上下文菜单逐个添加到列表中的每个项目。没有更好的解决方法吗?也许除了ListBox还有另一个控件? – rafale
可以使用DataGrid控件在WPF上市。您还可以添加文本菜单像
<DataGrid AutoGenerateColumns="False" Height="200" Width="200" >
<DataGrid.ContextMenu>
<ContextMenu >
<MenuItem Header="Menu Header" Click="MenuItem_Click" />
</ContextMenu>
</DataGrid.ContextMenu>
</DataGrid>
你可以发表你的XAML? 'ListBoxItem'具有'ContextMenu'属性,因此它应该可以正常工作 – kenwarner
@qntmfred:请参阅Meleak对我使用的XAML的文章。我以前的代码可能没有正确实施。 – rafale