我在C#WPF中做一个项目,包括客户端管理,我在其中添加新客户端,并且保存在txt文档中,我有一个listview,我可以看到所有已经添加的客户端,但是现在我想实现一个删除按钮,我从列表视图中选择一个客户端,并可以删除它。我现在不这样做,如果我能做到这一点,如果有人可以帮助我......,谢谢。
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void button_Voltar_Click(object sender, RoutedEventArgs e)
{
MainWindow mw = new MainWindow();
mw.Show();
this.Close();
}
private void button_Listar_Click(object sender, RoutedEventArgs e)
{
List<Cliente> clientes = new List<Cliente>();
string[] lines = File.ReadAllLines(@"C:\Users\Rui\Documents\Visual Studio 2015\Projects\Gestão Clientes Empresas\dadosClientes.txt");
foreach (string line in lines)
{
string[] parts = line.Split(';');
Cliente a = new Cliente();
a.Nome = parts[0];
a.Nif = parts[1];
a.Morada = parts[2];
clientes.Add(a);
}
listView.ItemsSource = clientes;
}
private bool myTextFilter(object item)
{
if (String.IsNullOrEmpty(textBox_pesquisa.Text))
return true;
var cliente = (Cliente)item;
return (cliente.Nome.StartsWith(textBox_pesquisa.Text, StringComparison.OrdinalIgnoreCase));
}
private void textBox_pesquisa_TextChanged_1(object sender, TextChangedEventArgs e)
{
ICollectionView view = CollectionViewSource.GetDefaultView(listView.ItemsSource);
view.Filter = new Predicate<object>(myTextFilter);
}
private void button_Apagar_Click(object sender, RoutedEventArgs e) \\Delete Button!
{
listView.Items.RemoveAt(listView.Items.IndexOf(listView.SelectedItems[0]));
}
}
答案 0 :(得分:0)
您可以使用ObservableCollection
:
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void button_Voltar_Click(object sender, RoutedEventArgs e)
{
MainWindow mw = new MainWindow();
mw.Show();
this.Close();
}
private readonly ObservableCollection<Cliente> clientes = new ObservableCollection<Cliente>();
private void button_Listar_Click(object sender, RoutedEventArgs e)
{
string[] lines = File.ReadAllLines(@"C:\Users\Rui\Documents\Visual Studio 2015\Projects\Gestão Clientes Empresas\dadosClientes.txt");
foreach (string line in lines)
{
string[] parts = line.Split(';');
Cliente a = new Cliente();
a.Nome = parts[0];
a.Nif = parts[1];
a.Morada = parts[2];
clientes.Add(a);
}
listView.ItemsSource = clientes;
}
private bool myTextFilter(object item)
{
if (String.IsNullOrEmpty(textBox_pesquisa.Text))
return true;
var cliente = (Cliente)item;
return (cliente.Nome.StartsWith(textBox_pesquisa.Text, StringComparison.OrdinalIgnoreCase));
}
private void textBox_pesquisa_TextChanged_1(object sender, TextChangedEventArgs e)
{
ICollectionView view = CollectionViewSource.GetDefaultView(listView.ItemsSource);
view.Filter = new Predicate<object>(myTextFilter);
}
private void button_Apagar_Click(object sender, RoutedEventArgs e)
{
Cliente client = listView.SelectedItem as Cliente;
if(client != null)
clientes.Remove(client);
}
}