以下代码实现了DataGrid的简单绑定List数据源

重点要提一下的是,绑定List数据源,但是不能直接用List。比如下面的代码,使用List<GridItem>只能实现数据修改的绑定,但是数据添加,删除都无法实现双向绑定。所以这里要改用ObservableCollection<GridItem>,其他代码都不用改。只要类型改下即可,WPF内部已经实现了添加,删除等的双向绑定功能。

接下去,就直接上代码了....

1、Model

public class GridModel
{ public GridModel()
{
GridData = new ObservableCollection<GridItem>();
}
public ObservableCollection<GridItem> GridData
{
get
{
return _griddata;
}
set
{
_griddata = value;
}
} private ObservableCollection<GridItem> _griddata;
}
GridItem数据类
public class GridItem : INotifyPropertyChanged
{
public GridItem(string name, string sex, bool chk = false)
{
Name = name;
Sex = sex;
UserChecked = chk;
}
public string Name
{
get { return _name; }
set {
if (_name != value)
{
_name = value;
OnPropertyChanged("Name");
}
}
}
public string Sex
{
get { return _sex; }
set
{
if (_sex != value)
{
_sex = value;
OnPropertyChanged("Sex");
}
}
}
public bool UserChecked
{
get { return _userchecked; }
set
{
if (_userchecked != value)
{
_userchecked = value;
OnPropertyChanged("UserChecked");
}
}
} public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
} private string _name;
private string _sex;
private bool _userchecked;
}

2、ViewModel

public class GridViewModel
{
public GridViewModel()
{
GridSource = new GridModel();
GridSource.GridData.Add(new GridItem("王路飞", "男"));
GridSource.GridData.Add(new GridItem("娜美", "女", true));
AddCommand = new DelegateCommand(Add, (obj) => true);
DecCommand = new DelegateCommand(Dec, (obj) => true);
ModifyCommand = new DelegateCommand(Modify, (obj) => true);
ShowCommand = new DelegateCommand(Show, (obj) => true);
}
public GridModel GridSource
{ get; set; } public ICommand AddCommand
{ get; set; }
public ICommand DecCommand
{ get; set; }
public ICommand ModifyCommand
{ get; set; }
public ICommand ShowCommand
{ get; set; } private void Add(object obj)
{
GridSource.GridData.Add(new GridItem("Luffy", "man",true));
}
private void Dec(object obj)
{
GridSource.GridData.RemoveAt();
}
private void Modify(object obj)
{
GridSource.GridData[].Name = "路飞";
GridSource.GridData[].Sex = "女";
GridSource.GridData[].UserChecked = true;
}
private void Show(object obj)
{
MessageBox.Show(GridSource.GridData[].Name + "," + GridSource.GridData[].Sex + "," + GridSource.GridData[].UserChecked);
}
}

3、XMAL

<Grid>
<TextBox x:Name="textBox" HorizontalAlignment="Left" Height="23" Margin="27,25,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120">
</TextBox>
<Label x:Name="label" Content="Label" Margin="173,23,79,0" VerticalAlignment="Top"/>
<Label x:Name="label1" Content="Label" Margin="233,23,19,0" VerticalAlignment="Top"/>
<DataGrid x:Name="dataGrid" Margin="16,71,19,44" ItemsSource="{Binding GridSource.GridData}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTemplateColumn Header="选中" Width="40">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding UserChecked, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"></CheckBox>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Header="用户名" Width="80" Binding="{Binding Name, Mode=TwoWay}"/>
<DataGridTextColumn Header="用户性别" Width="80" Binding="{Binding Sex, Mode=TwoWay}"/>
</DataGrid.Columns>
</DataGrid>
<Button x:Name="button" Content="添加" Command="{Binding AddCommand}" HorizontalAlignment="Left" Margin="16,0,0,5" Width="53" Height="29" VerticalAlignment="Bottom"/>
<Button x:Name="button_Copy" Content="删除" Command="{Binding DecCommand}" HorizontalAlignment="Left" Margin="83,0,0,5" Width="53" Height="29" VerticalAlignment="Bottom"/>
<Button x:Name="button_Copy1" Content="修改" Command="{Binding ModifyCommand}" HorizontalAlignment="Left" Margin="151,0,0,5" Width="53" Height="29" VerticalAlignment="Bottom"/>
<Button x:Name="button_Copy2" Content="显示" Command="{Binding ShowCommand}" HorizontalAlignment="Left" Margin="220,0,0,5" Width="53" Height="29" VerticalAlignment="Bottom"/> </Grid>

4、后台代码

 this.DataContext = new ViewModel.GridViewModel();

功能补充:一个文本框绑定2个属性X+Y形式

1、XMAL修改,主要是绑定使用MultiBinding (红色是新增的)

<Window x:Class="AddMessage.BindingTest"
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:AddMessage"
xmlns:localmodel="clr-namespace:AddMessage.Model"
mc:Ignorable="d"
Title="BindingTest" Height="" Width="" WindowStartupLocation="CenterScreen">
<Window.Resources>
<localmodel:TextConverter x:Key="TxtConvert"></localmodel:TextConverter>
</Window.Resources>
<Grid>
<TextBox x:Name="textBox" HorizontalAlignment="Left" Height="23" Margin="27,25,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120">
<TextBox.Text>
<MultiBinding Converter="{StaticResource TxtConvert}">
<Binding Path="Text" ElementName="lblleft"/>
<Binding Path="Text" ElementName="lblright"/>
</MultiBinding>
</TextBox.Text>
</TextBox>
<TextBox x:Name="lblleft" Text="1" Margin="173,23,79,0" Height="25" VerticalAlignment="Top"/>
<TextBox x:Name="lblright" Text="2" Margin="233,23,19,0" Height="25" VerticalAlignment="Top"/>
<DataGrid x:Name="dataGrid" Margin="16,71,19,44" ItemsSource="{Binding GridSource.GridData}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTemplateColumn Header="选中" Width="">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding UserChecked, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"></CheckBox>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Header="用户名" Width="" Binding="{Binding Name, Mode=TwoWay}"/>
<DataGridTextColumn Header="用户性别" Width="" Binding="{Binding Sex, Mode=TwoWay}"/>
</DataGrid.Columns>
</DataGrid>
<Button x:Name="button" Content="添加" Command="{Binding AddCommand}" HorizontalAlignment="Left" Margin="16,0,0,5" Width="" Height="" VerticalAlignment="Bottom"/>
<Button x:Name="button_Copy" Content="删除" Command="{Binding DecCommand}" HorizontalAlignment="Left" Margin="83,0,0,5" Width="" Height="" VerticalAlignment="Bottom"/>
<Button x:Name="button_Copy1" Content="修改" Command="{Binding ModifyCommand}" HorizontalAlignment="Left" Margin="151,0,0,5" Width="" Height="" VerticalAlignment="Bottom"/>
<Button x:Name="button_Copy2" Content="显示" Command="{Binding ShowCommand}" HorizontalAlignment="Left" Margin="220,0,0,5" Width="" Height="" VerticalAlignment="Bottom"/> </Grid>
</Window>

2、TextConverter 格式转换类,即处理,将2个文本合并成一个文本

public class TextConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
string val = "";
foreach (var v in values)
{
if (val == "")
val = v.ToString();
else
val += "+" + v;
}
return val;
} public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
string val = value.ToString();
string[] vals = val.Split('+');
return vals;
}
}

【WPF】WPF DataGrid List数据源 双向绑定通知机制之ObservableCollection使用以及MultiBinding 的应用的更多相关文章

  1. WPF 中双向绑定通知机制之ObservableCollection使用

    msdn中   ObservableCollection<T> 类    表示一个动态数据集合,在添加项.移除项或刷新整个列表时,此集合将提供通知. 在许多情况下,所使用的数据是对象的集合 ...

  2. WPF之Treeview实现MVVM双向绑定

    Treeview分别有两个数据模板HierarchicalDataTemplate(层级数据模板)和DataTemplate(数据模板),分别应用于生成子数据项和普通数据项. 在使用过程中,如果对两个 ...

  3. WPF的DataGrid的某个列绑定数据的三种方法(Binding、Converter、DataTrigger)

    最近在使用WPF的时候,遇到某个列的值需要根据内容不同进行转换显示的需求.尝试了一下,大概有三种方式可以实现: 1.传统的Binding方法,后台构造好数据,绑定就行. 2.转换器方法(Convert ...

  4. WPF之AvalonEdit实现MVVM双向绑定

    AvalonEdit简介 AvalonEdit是基于WPF开发的代码显示控件,默认支持多种不同语言的关键词高亮,并且可以自定义高亮配置.所以通过AvalonEdit可以快速开发出自己想要的代码编辑器. ...

  5. WPF数据双向绑定

    设置双向绑定,首先控件要绑定的对象要先继承一个接口: INotifyPropertyChanged 然后对应被绑定的属性增加代码如下: 意思就是当Age这个属性变化时,要通知监听它变化的人. 即:Pr ...

  6. WPF的DataGrid绑定ItemsSource后第一次加载数据有个别列移位的解决办法

    最近用WPF的DataGrid的时候,发现一个很弱智的问题,DataGrid的ItemsSource是绑定了一个属性: 然后取数给这个集合赋值的时候,第一次赋值,就会出现列移位 起初还以为是显卡的问题 ...

  7. C# Wpf集合双向绑定

    说明: msdn中   ObservableCollection<T> 类    表示一个动态数据集合,在添加项.移除项或刷新整个列表时,此集合将提供通知. 在许多情况下,所使用的数据是对 ...

  8. C# Wpf双向绑定实例

    Wpf中双向绑定处理需要两处 实例1: 1.前台Xaml中属性Binding 时Model指定 TwoWay <Grid> <Ellipse x:Name="ellipse ...

  9. WPF中DataGrid的ComboBox的简单绑定方式(绝对简单)

    在写次文前先不得不说下网上的其他wpf的DataGrid绑定ComboBox的方式,看了之后真是让人欲仙欲死. 首先告诉你一大堆的模型,一大堆的控件模板,其实或许你紧紧只想知道怎么让combobox怎 ...

随机推荐

  1. 浅谈HTML5 WebSocket的机制

    回想上一章 在上一章<为什么我们须要HTML5 WebSocket>中,我简单的介绍了下WebSocket的前世今生.相信大家已对WebSocket有了初步的了解.那么今天我们继续深入学习 ...

  2. 加快android studio 编译速度(已更新至Android Studio 3.3.1)

    1.加快AS启动速度 “Help”-"Edit Custom Properties...",在文件中输入 # custom Android Studio properties di ...

  3. 【Android】Sensor框架HAL层解读

    Android sensor构建 Android4.1 系统内置对传感器的支持达13种,他们分别是:加速度传感器(accelerometer).磁力传感器(magnetic field).方向传感器( ...

  4. (精品)微信支付android端

    PayingActivity.java public void WxPay(){ // new Thread(new Runnable() { // @Override // public void ...

  5. Node.js学习笔记(3)--url.parse方法

    说明(2017-5-2 14:23:47): 1. index.html <!DOCTYPE html> <html lang="en"> <head ...

  6. Sortable拖拽排序插件数据筛选

    后台有拖拽排序功能,然而前段在开发的时候,一整页的数据都发给后端了. 于是查看前端代码,想到了如下解决办法,即先把排序前的保存,然后对比排序后的,有差异的才发回给后端. var new_ids_ord ...

  7. 用Python从零开始实现K近邻算法

    KNN算法的定义: KNN通过测量不同样本的特征值之间的距离进行分类.它的思路是:如果一个样本在特征空间中的k个最相似(即特征空间中最邻近)的样本中的大多数属于某一个类别,则该样本也属于这个类别.K通 ...

  8. Android 开发自己的网络收音机2——电台列表(SlidingMenu侧滑栏)

    上一篇文章总体规划了这个项目的情况,今天讲讲实现电台列表.今天其实主要想讲解的是SlidingMenu,也就是我们平时说的侧滑栏,现在很多应用都有用这种UI效果.SlidingMenu侧滑栏功能实现的 ...

  9. linux 删除文件,df空间不变化

    今天遇到一个问题,就是linux服务器空间满了,可是删除了软件后. 查看空间,没有变化 ???啥情况 那么去查看删除的情况吧. [root@VM_0_4_centos usr]# lsof|grep ...

  10. regsvr32.exe是什么东西

    Regsvr32命令修复系统故障实例使用过activex的人都知道,activex不注册是不能够被系统识别和使用的,一般安装程序都会自动地把它所使用的activex控件注册,但如果你拿到的一个控件需要 ...