以下代码实现了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. 深入详解JVM内存模型与JVM参数详细配置

    对于大多数应用来说,Java 堆(Java Heap)是Java 虚拟机所管理的内存中最大的一块.Java 堆是被所有线程共享的一块内存区域,在虚拟机启动时创建. JVM内存结构 由上图可以清楚的看到 ...

  2. 【delphi】Byte数组与String类型的转换

    string string = AnsiString = 长字符串,理论上长度不受限制,但其实受限于最大寻址范围2的32次方=4G字节: 变量Str名字是一个指针,指向位于堆内存的字符序列,字符序列起 ...

  3. nginx源码分析:打开监听套接字的流程

    问题源于在分析nginx的源码时,找了半天没有找到nginx是怎么把监听套接字读事件添加到事件循环中的,后经过仔细的分析,终于搞明白,于是记录一下. 在上一篇module机制中介绍了nginx添加mo ...

  4. Android studio动态调试

    Reference:  http://cstsinghua.github.io/2016/06/13/Android%20studio%E5%8A%A8%E6%80%81%E8%B0%83%E8%AF ...

  5. python 视频处理,提取视频相关帧,读取Excel

    一共这几个模块: class videoReader 读取视频 class videoFramesExtractor(videoReader):继承了读取视频,主要是用来限制读取视频中的哪些帧,并保存 ...

  6. C#学习笔记(4)——sqlserver常用语句

    说明(2017-5-26 17:29:05): 需要天天练习: 新建表:create table [表名]([自动编号字段] int IDENTITY (1,1) PRIMARY KEY ,[字段1] ...

  7. iOS APP版本更新跳转到App Store下载/更新方法

    使用下面的连接即可跳转到App Store itms-apps://itunes.apple.com/cn/app/id***********                  其中********* ...

  8. 慢速HTTP拒接服务攻击(DoS)复现

    kali linux下有个神奇的工具叫“slowhttptest” 命令:slowhttptest -c 1000 -H -g -o slowhttp -i 10 -r 200 -t GET -u h ...

  9. WebAPI Action的几种返回值类型

    void 返回204状态码 HttpResponseMessage Convert directly to an HTTP response message. IHttpActionResult Ca ...

  10. plot sin示意图(隐藏刻度,自定义刻度)

    plot sin示意图(隐藏刻度,自定义刻度) 隐藏坐标轴刻度 自定义坐标轴刻度 Code #!/usr/bin/env python # -*- coding: utf-8 -*- import n ...