WPF 使用DataGrid绑定数据,并添加编辑和删除按钮
程序员文章站
2023-12-28 10:26:40
...
xaml
<DataGrid Name="userList" AutoGenerateColumns="False" CanUserAddRows="False">
<DataGrid.Columns>
<DataGridTextColumn Header="用户名" Width="800" Binding="{Binding name}" />
<DataGridTextColumn Header="工 号" Binding="{Binding user_sn}" />
<DataGridTextColumn Header="时 间" Binding="{Binding created_at}" />
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Button Content="编 辑" Tag="{Binding id}" Click="UserEditClick" />
<Button Content="删 除" Tag="{Binding id}" Click="UserDeleteClick" />
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
使用DataGridTemplateColumnkey在一列添加多个控件,这里添加了2个按钮,编辑和删除
数据绑定,直接从DataTable中读取数据绑定
UserViewModel userModel = new UserViewModel();
this.userList.ItemsSource = userModel.GetUser().DefaultView;
编辑
我使用了页面跳转编辑,觉得这样好看点,用弹窗感觉不好看
private void UserEditClick(object sender, RoutedEventArgs e)
{
Button btn = sender as Button;
if (btn != null)
{
int id = Convert.ToInt32(btn.Tag);
User user = new User(id);
this.NavigationService.Navigate(user);
}
}
编辑页面需要多一个构造函数接收参数
public User(int id)
{
InitializeComponent();
if (id != 0)
{
this._id = id;
EditUserInit(this._id);
}
}
编辑直接从DataRow中读取数据
public void EditUserInit(int id)
{
UserViewModel userModel = new UserViewModel();
Dictionary<string, object> user = userModel.GetUserRowById(id);
this.nameTxt.Text = user["name"].ToString();
this.userSnTxt.Text = user["user_sn"].ToString();
}
删除
private void UserDeleteClick(object sender, RoutedEventArgs e)
{
Button btn = sender as Button;
if (btn != null)
{
int id = Convert.ToInt32(btn.Tag);
UserViewModel userModel = new UserViewModel();
userModel.DeleteUser(id);
MessageBox.Show("删除成功");
this.userList.ItemsSource = userModel.GetUser().DefaultView;
}
}