带有ContextMenu的WPF ListView不使用数据绑定显示数据,可以通过以下步骤实现:
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WPF ListView with ContextMenu" Height="450" Width="800">
<Grid>
<ListView x:Name="listView">
<ListView.View>
<GridView>
<GridViewColumn Header="Name" Width="120" DisplayMemberBinding="{Binding Name}" />
<GridViewColumn Header="Age" Width="50" DisplayMemberBinding="{Binding Age}" />
</GridView>
</ListView.View>
</ListView>
<ContextMenu x:Name="contextMenu">
<MenuItem Header="Delete" Click="Delete_Click" />
</ContextMenu>
</Grid>
</Window>
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
// 创建数据
List<Person> people = new List<Person>
{
new Person { Name = "John", Age = 25 },
new Person { Name = "Jane", Age = 30 },
new Person { Name = "Bob", Age = 35 }
};
// 将数据添加到ListView中
foreach (Person person in people)
{
listView.Items.Add(person);
}
}
// 右键菜单的点击事件处理程序
private void Delete_Click(object sender, RoutedEventArgs e)
{
// 在这里处理删除操作
if (listView.SelectedItem != null)
{
listView.Items.Remove(listView.SelectedItem);
}
}
}
通过以上步骤,你可以创建一个带有ContextMenu的WPF ListView,并在不使用数据绑定的情况下显示数据。右键点击ListView中的项时,会触发删除操作。你可以根据实际需求进行修改和扩展。
领取专属 10元无门槛券
手把手带您无忧上云