以下代码实现了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. 深入理解Linux内核-内存寻址

    1.逻辑地址怎么转换为线性地址的: 逻辑地址 = 段选择符(16bit)+偏移量(32bit) 段选择符又三部分组成:index(索引序号).T1(表指示器).RPL(request privileg ...

  2. innobackupex在线备份及恢复(全量和增量)

    Xtrabackup是由percona开发的一个开源软件,它是innodb热备工具ibbackup(收费的商业软件)的一个开源替代品.Xtrabackup由个部分组成:xtrabackup和innob ...

  3. [SQL in Azure] Getting Started with SQL Server in Azure Virtual Machines

    This topic provides guidelines on how to sign up for SQL Server on a Azure virtual machine and how t ...

  4. 【驱动】input子系统全面分析

    初识linux输入子系统 linux输入子系统(linux input subsystem)从上到下由三层实现,分别为:输入子系统事件处理层(EventHandler).输入子系统核心层(InputC ...

  5. window.opener方法的使用 js 跨域

    用到了这个方法: window.opener.location.reload() 与 window.opener.location.href=window.opener.location.href 都 ...

  6. IP段对应表

    IP段对应表   IP总数 子网掩码 C段个数 /30 4 255.255.255.252 1/64 /29 8 255.255.255.248 1/32 /28 16 255.255.255.240 ...

  7. PHP中的WebService

    Web Service技术, 能使得运行在不同机器上的不同应用无须借助附加的.专门的第三方软件或硬件, 就可相互交换数据或集成.依据Web Service规范实施的应用之间, 无论它们所使用的语言. ...

  8. css3 data-attribute属性打造漂亮的按钮

    之前介绍了几款css3实现的按钮,今天为网友来款比较新鲜的,用css3的data-attribute属性开发按钮,当鼠标经过显示按钮的详细信息.而且实现过程很简单,几行代码就搞定.大家试一试吧.如下图 ...

  9. spring @Bean注解解释

    解释:java config配置一个重要注解 @Bean明确地指示了一种方法,什么方法呢——产生一个bean的方法,并且交给Spring容器管理:从这   我们就明白了为啥@Bean是放在方法的注释上 ...

  10. Mongo分区后分片下count记录不准确

    问题描述 问题如图,后来上网查了一下,发现了这是正常现象: 官方文档解释了这种现象的原因以及解决方法: 不准确的原因: 操作的是分片的集合(前提): shard分片正在做块迁移,导致有重复数据出现 存 ...