1.概要
1.1 需求
一个列表提供添加修改删除的功能,添加和修改的内容都来自一个输入框
1.2 要点
- DisplayMemberPath="Zhi"
- 列表.ItemsSource = datalist;
- (列表.SelectedItem != null)
- (列表.SelectedItem as A).Zhi = 内容.Text;
- datalist.Remove((列表.SelectedItem as A)!);
- public String? Zhi { get { return _zhi; } set { _zhi = value; OnPropertyChanged(nameof(Zhi)); } }
- PropertyChanged.Invoke(this, new PropertyChangedEventArgs(name));
2.代码
2.1 xaml
<Window x:Class="WpfApp5.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local="clr-namespace:WpfApp5"mc:Ignorable="d"Title="MainWindow" Height="450" Width="800"><StackPanel><TextBox Name="内容" ></TextBox><Button Name="Add" Content="添加" Click="Add_Click" /><Button Name="Update" Content="修改" Click="Update_Click" /><Button Name="Delete" Content="删除" Click="Delete_Click" /><ListBox Name="列表" DisplayMemberPath="Zhi" Height="100"></ListBox></StackPanel>
</Window>
2.2 代码
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;namespace WpfApp5
{/// <summary>/// Interaction logic for MainWindow.xaml/// 连表数据绑定/// </summary>public partial class MainWindow : Window{ObservableCollection<A> datalist = new ObservableCollection<A>();//List<A> datalist = new List<A>();public MainWindow(){InitializeComponent();init();}private void init(){datalist.Add(new A { Zhi = "1" });datalist.Add(new A { Zhi = "2" });datalist.Add(new A { Zhi = "3" });//列表.DataContext = datalist;列表.ItemsSource = datalist;}private void Add_Click(object sender, RoutedEventArgs e){datalist.Add(new A { Zhi = 内容.Text });}private void Update_Click(object sender, RoutedEventArgs e){if (列表.SelectedItem != null){(列表.SelectedItem as A).Zhi = 内容.Text;}}private void Delete_Click(object sender, RoutedEventArgs e){if (列表.SelectedItem != null){datalist.Remove((列表.SelectedItem as A)!);}}}class A:INotifyPropertyChanged{private String? _zhi;public String? Zhi { get { return _zhi; } set { _zhi = value; OnPropertyChanged(nameof(Zhi)); } }public event PropertyChangedEventHandler? PropertyChanged;private void OnPropertyChanged(String name){if (PropertyChanged != null){PropertyChanged.Invoke(this, new PropertyChangedEventArgs(name));}}}
}