以下代码实现了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. android使用百度地图SDK 去掉百度Logo的小技巧

    // 隐藏logoView child = mMapView.getChildAt(1); if (child != null && (child instanceof ImageVi ...

  2. .NET+MVC+Alipay的Sdk版单笔转账到支付宝账户接口

    public class AliPayController : Controller { // GET: AliPay public ActionResult Index() { return Red ...

  3. django rest_framework入门四-类视图APIView

    上节,我们使用函数视图,用了@api_view装饰器来修饰,这一节,我们介绍类视图APIView,显然,类视图更符合面向对象的原则. 1.使用类视图APIView重写API 类视图APIView,取代 ...

  4. Spring和Mybatis整合过程中遇到的一个找不到sqlSessionFactory或sqlSessionTemplate的异常

    先看启动web项目时IDEA控制台抛出的异常(红色部分): D:\tomcat-kafka-\bin\catalina.bat run [-- ::,] Artifact Gradle : com.x ...

  5. FIDDLER的使用方法及技巧总结(连载一)FIDDLER快速入门及使用场景

    FIDDLER的使用方法及技巧总结 一.FIDDLER快速入门及使用场景 Fiddler的官方网站:http://www.fiddler2.com Fiddler的官方帮助:http://docs.t ...

  6. hdu1102(最小生成树水题)

    #include<iostream> #include<cstdio> #include<cstring> #include<algorithm> us ...

  7. 判断URL文件是不是在于在。

    判断URL文件是不是在于在. private static bool UrlIsExist(string url) { System.Uri u = null; try { u = new Uri(u ...

  8. java判断是移动端还是pc端

    // \b 是单词边界(连着的两个(字母字符 与 非字母字符) 之间的逻辑上的间隔), // 字符串在编译时会被转码一次,所以是 "\\b" // \B 是单词内部逻辑间隔(连着的 ...

  9. Ubuntu 安装 vnc server

    安装原因,因为需要有桌面操作, 服务器上配置 vnc 即可实现. 在 ubuntu 14.04 上已经实现. 安装先关软件 sudo apt-get update sudo apt-get insta ...

  10. TCP和UDPsocket中SO_SNDBUF和SO_RCVBUF_转

    1.Background Winsock kernel buffer To optimize performance at the application layer, Winsock copies ...