列表框和上下文菜单的 WPF 数据模板
WPF Data template for Listbox and Context menu
我正在尝试使用数据模板创建一个带有上下文菜单的列表。
到目前为止,我有以下代码:
<ListBox>
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}"/>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.Items>
<sys:String>Item 1</sys:String>
<sys:String>Item 2</sys:String>
</ListBox.Items>
</Listbox>
我想添加以下上下文菜单:
<ContextMenu>
<MenuItem Header="Edit" />
<MenuItem Header="Delete" />
</ContextMenu>
我曾尝试使用 ListBox.ItemContainerStyle 和 Setter,但我正在使用 Material Design,当我使用样式 setter 时,它会带走那些 material设计风格。
解决方案:
<ListBox>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Background="Transparent">
<TextBlock Text="{Binding}"/>
</StackPanel>
<StackPanel.ContextMenu>
<ContextMenu>
<MenuItem Header="Edit" />
<MenuItem Header="Delete" />
</ContextMenu>
</StackPanel.ContextMenu>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.Items>
<sys:String>Item 1</sys:String>
<sys:String>Item 2</sys:String>
</ListBox.Items>
</Listbox>
或使用 BasedOn 属性 和 ListBox.ItemContainerStyle。
我正在尝试使用数据模板创建一个带有上下文菜单的列表。 到目前为止,我有以下代码:
<ListBox>
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}"/>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.Items>
<sys:String>Item 1</sys:String>
<sys:String>Item 2</sys:String>
</ListBox.Items>
</Listbox>
我想添加以下上下文菜单:
<ContextMenu>
<MenuItem Header="Edit" />
<MenuItem Header="Delete" />
</ContextMenu>
我曾尝试使用 ListBox.ItemContainerStyle 和 Setter,但我正在使用 Material Design,当我使用样式 setter 时,它会带走那些 material设计风格。
解决方案:
<ListBox>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Background="Transparent">
<TextBlock Text="{Binding}"/>
</StackPanel>
<StackPanel.ContextMenu>
<ContextMenu>
<MenuItem Header="Edit" />
<MenuItem Header="Delete" />
</ContextMenu>
</StackPanel.ContextMenu>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.Items>
<sys:String>Item 1</sys:String>
<sys:String>Item 2</sys:String>
</ListBox.Items>
</Listbox>
或使用 BasedOn 属性 和 ListBox.ItemContainerStyle。