如何删除WPF中显示在ListView中的特定文本

本文关键字:ListView 文本 显示 删除 WPF 何删除 | 更新日期: 2023-09-27 17:49:22

我看过这个话题:如何删除显示在ListView中的特定文本/消息?

它在winform中工作得很好(我已经测试过了!),但在WPF中不起作用。

我想在listview1中找到firstnametext的文本,并将其与Firstname列项目进行比较,如果其为真,则删除该项目(包含该项的行)

但是我不知道如何在WPF中处理这个

我的部分代码是这样的:

XAML:

<ListView Name="listView1 HorizontalAlignment="Left" VerticalAlignment="Top" />
    <ListView.View>
        <GridView>
            <GridViewColumn Header="FirstName" DisplayMemberBinding="{Binding Path=FirstName}"  />
            <GridViewColumn Header="LastName" DisplayMemberBinding="{Binding Path=LastName}" />
        </GridView>
    </ListView.View>
</ListView>
<TextBox Name="firstnametxt" Height="27" HorizontalAlignment="Left" Margin="271,20,0,0"  VerticalAlignment="Top" Width="181" />
<Button Content="Add" Height="38" HorizontalAlignment="Left" Margin="310,242,0,0" Name="button1" VerticalAlignment="Top" Width="74" Click="button1_Click" />
<Button Content="Find" Height="38" HorizontalAlignment="Left" Name="button2" VerticalAlignment="Top" Width="74" Click="button2_Click" />

背后代码(c#):

public class Familiy
{
    public Familiy(string firstname, string lastname)
    {
        this.FirstName = firstname;
        this.LastName = lastname;
    }
    private string firstname;
    public string FirstName
    {
        get { return firstname; }
        set { firstname = value; }
    }
    private string lastname;
    public string LastName
    {
        get { return lastname; }
        set { lastname = value; }
    }
}

private void button1_Click(object sender, RoutedEventArgs e)
{ 
    ///////////////////////////
}

如何删除WPF中显示在ListView中的特定文本

你需要改变ListBox的ItemSource,无论它是一个ItemList, List还是其他的集合类型。

public partial class MainWindow : Window
{
    List<Familiy> familiys = new List<Familiy>();
    public MainWindow()
    {
        InitializeComponent();

        familiys.Add( new Familiy("FirstName1", "LastName1"));
        familiys.Add(new Familiy("FirstName2", "LastName2"));
        familiys.Add(new Familiy("FirstName3", "LastName3"));
        familiys.Add(new Familiy("FirstName4", "LastName4"));
        listView1.ItemsSource = familiys;
    }
    private void button1_Click(object sender, RoutedEventArgs e)
    {
        familiys.Remove(familiys.Find(delegate(Familiy f) { return f.FirstName == firstnametxt.Text; }));
        listView1.ItemsSource = "";
        listView1.ItemsSource = familiys;
    }
}