WPF-DataGrid增删改查绑定数据源
Posted wangyinlon
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了WPF-DataGrid增删改查绑定数据源相关的知识,希望对你有一定的参考价值。
Xaml
<DataGrid Height="200"
Name="dataGrid1"
Margin="5,0,5,0"
VerticalAlignment="Top"
AlternationCount="2"
AutoGenerateColumns="False"
CanUserAddRows="False"
CanUserDeleteRows="False"
CanUserReorderColumns="False"
CanUserResizeColumns="False"
CanUserResizeRows="False"
CanUserSortColumns="False"
IsReadOnly="True"
RowHeaderWidth="0"
SelectionMode="Single">
<DataGrid.Columns>
<DataGridTextColumn Width="8*" Header="账号" Binding="{Binding Name}"></DataGridTextColumn>
<DataGridTemplateColumn Width="2*" Header="状态" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock
Margin="0,0,0,0"
Foreground="#666666"
Text="{Binding Age}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
建立实体类
public class User : INotifyPropertyChanged
{
private string name;
public string Name
{
get
{
return name;
}
set
{
name = value;
OnPropertyChanged("Name");
}
}
public string Age { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
增删改
private void add_Click(object sender, RoutedEventArgs e)
{
//修改数据源后需手动重新赋值
datalist.Add(new User ());
dataGrid1.ItemsSource = null;
dataGrid1.ItemsSource = datalist;
}
private void delete_Click(object sender, RoutedEventArgs e)
{
if (dataGrid1.SelectedIndex >= 0)
{
//修改数据源后需手动重新赋值
datalist.RemoveAt(dataGrid1.SelectedIndex);
dataGrid1.ItemsSource = null;
dataGrid1.ItemsSource = datalist;
}
}
private void update_Click(object sender, RoutedEventArgs e)
{
if (dataGrid1.SelectedIndex >= 0)
{
//修改前台后数据源也会一起改变
SubRowsId().Name = "update";
}
}
#region 获取选中行的原始值
/// <summary>
/// 获取选中行的原始值
/// </summary>
/// <param name="rowindex"></param>
private User SubRowsId()
{
return (User)dataGrid1.SelectedItem;
}
#endregion
以上是关于WPF-DataGrid增删改查绑定数据源的主要内容,如果未能解决你的问题,请参考以下文章
求.net 连ORACLE数据库 增删改查完整代码 代码 要最简单的
DataSet之增删改查操作(DataGridView绑定)
Express实战 - 应用案例- realworld-API - 路由设计 - mongoose - 数据验证 - 密码加密 - 登录接口 - 身份认证 - token - 增删改查API(代码片段