c# - 如何删除 WPF 中 ListView 中显示的特定文本?

标签 c# wpf listview

我读过这个主题: how to delete a specific text / message showed in a ListView ?

它在 winform 中工作正常(我已经测试过了!)但在 WPF 中它不起作用。

我想在 listview1 中找到 firstnametxt 的文本并将其与 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)
{ 
    ///////////////////////////
}

最佳答案

您需要更改 ListBox ItemSsource,无论它是 ItemList、List 还是其他集合类型,此示例使用 Family 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;
    }
}

关于c# - 如何删除 WPF 中 ListView 中显示的特定文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14024836/

相关文章:

c# - 如何删除按钮运行时间?

c# - 如何在 MVC 的 DropDownList 中将默认值 "0"设置为文本 "Select"?

c# - 将 GetKeyNameText 与特殊键一起使用

c# - NetworkStream 不刷新数据

c# - 与多个从站通信(基于 Modbus 协议(protocol))

c# - 有没有办法在不使用后台线程的情况下更新进度条?

c# - 绑定(bind)到项目而不是列表框中的属性

java - 可选择的自定义ListView

android - getItemAtPosition() 不在 ListView 中返回值

android - 单击刷新按钮刷新 Activity 内容