最近在学习ItemsControl这个控件的时候,查看了MSDN上面的一个例子,并且自己做了一些修改,这里主要使用了两种方式来进行相应的数据绑定,一种是使用DataContext,另外一种是直接将一个类绑定到前台,其实这两种方式原理差不多都是将数据模型的对象添加到一个ObservableCollection集合中,然后再绑定到前台,下面分别介绍两种绑定方式:

第一种是将数据存储在一个ObservableCollection集合中,然后作为ItemsControl的DataContext对象,下面分别贴出相关的代码:

  1. <Window x:Class="TestGrid.MainWindow"
  2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4. xmlns:local="clr-namespace:TestGrid"
  5. Title="MainWindow" Height="" Width="">
  6. <Grid>
  7. <ItemsControl Margin="" x:Name="myItemsControl" ItemsSource="{Binding}">
  8. <ItemsControl.Template>
  9. <ControlTemplate TargetType="ItemsControl">
  10. <Border BorderBrush="Aqua" BorderThickness="" CornerRadius="">
  11. <ItemsPresenter/>
  12. </Border>
  13. </ControlTemplate>
  14. </ItemsControl.Template>
  15. <ItemsControl.ItemsPanel>
  16. <ItemsPanelTemplate>
  17. <WrapPanel/>
  18. </ItemsPanelTemplate>
  19. </ItemsControl.ItemsPanel>
  20. <ItemsControl.ItemTemplate>
  21. <DataTemplate DataType="{ x:Type local:DataSource}">
  22. <DataTemplate.Resources>
  23. <Style TargetType="TextBlock">
  24. <Setter Property="FontSize" Value=""/>
  25. <Setter Property="HorizontalAlignment" Value="Center"/>
  26. </Style>
  27. </DataTemplate.Resources>
  28. <Grid>
  29. <Rectangle Fill="Green"/>
  30. <Ellipse Fill="Red"/>
  31. <StackPanel>
  32. <TextBlock Margin="3,3,3,0" Text="{Binding Path=Priority,Mode=TwoWay}"/>
  33. <TextBlock Margin="3,0,3,7" Text="{Binding Path=TaskName,Mode=TwoWay}"/>
  34. </StackPanel>
  35. </Grid>
  36. </DataTemplate>
  37. </ItemsControl.ItemTemplate>
  38. <ItemsControl.ItemContainerStyle>
  39. <Style>
  40. <Setter Property="Control.Width" Value=""/>
  41. <Setter Property="Control.Margin" Value=""/>
  42. <Style.Triggers>
  43. <Trigger Property="Control.IsMouseOver" Value="True">
  44. <Setter Property="Control.ToolTip" Value="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=Content.Description}"/>
  45. </Trigger>
  46. </Style.Triggers>
  47. </Style>
  48. </ItemsControl.ItemContainerStyle>
  49. </ItemsControl>
  50. </Grid>
  51. </Window>

这里需要注意的地方是 ItemsSource="{Binding}"这句必须添加,否则后台的数据是无法添加到前台的,这个需要注意,这里贴出后台的代码

  1. using System.Windows.Documents;
  2. using System.Windows.Input;
  3. using System.Windows.Media;
  4. using System.Windows.Media.Imaging;
  5. using System.Windows.Navigation;
  6. using System.Windows.Shapes;
  7.  
  8. namespace TestGrid
  9. {
  10. /// <summary>
  11. /// MainWindow.xaml 的交互逻辑
  12. /// </summary>
  13. public partial class MainWindow : Window
  14. {
  15. private ObservableCollection<DataSource> item = null;
  16. public MainWindow()
  17. {
  18. InitializeComponent();
  19. item = new ObservableCollection<DataSource>();
  20. item.Add(
  21. new DataSource()
  22. {
  23. Priority = "",
  24. TaskName = "hello"
  25. }
  26. );
  27. item.Add(
  28. new DataSource()
  29. {
  30. Priority = "",
  31. TaskName = "whats"
  32. }
  33. );
  34. item.Add(
  35. new DataSource()
  36. {
  37. Priority = "",
  38. TaskName = "your"
  39. }
  40. );
  41. item.Add(
  42. new DataSource()
  43. {
  44. Priority = "",
  45. TaskName = "name"
  46. }
  47. );
  48. item.Add(
  49. new DataSource()
  50. {
  51. Priority = "",
  52. TaskName = "can"
  53. }
  54. );
  55. item.Add(
  56. new DataSource()
  57. {
  58. Priority = "",
  59. TaskName = "you"
  60. }
  61. );
  62. this.myItemsControl.DataContext = item;
  63.  
  64. }
  65. }
  66. }
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.ObjectModel;
  4. using System.ComponentModel;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8.  
  9. namespace TestGrid
  10. {
  11. public class DataSource : INotifyPropertyChanged
  12. {
  13. public event PropertyChangedEventHandler PropertyChanged;
  14. public DataSource()
  15. {
  16. }
  17.  
  18. private string priority;
  19. public string Priority
  20. {
  21. get
  22. {
  23. return priority;
  24. }
  25. set
  26. {
  27. priority = value;
  28. OnPropertyChanged("Priority");
  29. }
  30. }
  31.  
  32. private string taskname;
  33. public string TaskName
  34. {
  35. get
  36. {
  37. return taskname;
  38. }
  39. set
  40. {
  41. taskname = value;
  42. OnPropertyChanged("TaskName");
  43. }
  44. }
  45.  
  46. protected void OnPropertyChanged(string propName)
  47. {
  48. if (PropertyChanged != null)
  49. {
  50. PropertyChanged(this, new PropertyChangedEventArgs(propName));
  51. }
  52.  
  53. }
  54.  
  55. private List<DataSource> datasources;
  56.  
  57. public List<DataSource> DataSources
  58. {
  59. get { return datasources; }
  60. set { datasources = value; }
  61. }
  62.  
  63. }
  64. }

这里最重要的一句就是 this.myItemsControl.DataContext = item;这个是将刚才的集合绑定到ItemsControl控件上,这里需要我们的注意。

另外一种方式的数据绑定就是将一个类绑定到这个ItemsControl控件上,具体的方式如下:

  1. <Window x:Class="TestGrid.MainWindow"
  2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4. xmlns:local="clr-namespace:TestGrid"
  5. Title="MainWindow" Height="" Width="">
  6. <Window.Resources>
  7. <local:MyData x:Key="myDataSource"/>
  8. </Window.Resources>
  9. <Grid>
  10. <ItemsControl Margin="" x:Name="myItemsControl" ItemsSource="{Binding Source={StaticResource myDataSource}}">
  11. <ItemsControl.Template>
  12. <ControlTemplate TargetType="ItemsControl">
  13. <Border BorderBrush="Aqua" BorderThickness="" CornerRadius="">
  14. <ItemsPresenter/>
  15. </Border>
  16. </ControlTemplate>
  17. </ItemsControl.Template>
  18. <ItemsControl.ItemsPanel>
  19. <ItemsPanelTemplate>
  20. <WrapPanel/>
  21. </ItemsPanelTemplate>
  22. </ItemsControl.ItemsPanel>
  23. <ItemsControl.ItemTemplate>
  24. <DataTemplate DataType="{ x:Type local:DataSource}">
  25. <DataTemplate.Resources>
  26. <Style TargetType="TextBlock">
  27. <Setter Property="FontSize" Value=""/>
  28. <Setter Property="HorizontalAlignment" Value="Center"/>
  29. </Style>
  30. </DataTemplate.Resources>
  31. <Grid>
  32. <Rectangle Fill="Green"/>
  33. <Ellipse Fill="Red"/>
  34. <StackPanel>
  35. <TextBlock Margin="3,3,3,0" Text="{Binding Path=Priority,Mode=TwoWay}"/>
  36. <TextBlock Margin="3,0,3,7" Text="{Binding Path=TaskName,Mode=TwoWay}"/>
  37. </StackPanel>
  38. </Grid>
  39. </DataTemplate>
  40. </ItemsControl.ItemTemplate>
  41. <ItemsControl.ItemContainerStyle>
  42. <Style>
  43. <Setter Property="Control.Width" Value=""/>
  44. <Setter Property="Control.Margin" Value=""/>
  45. <Style.Triggers>
  46. <Trigger Property="Control.IsMouseOver" Value="True">
  47. <Setter Property="Control.ToolTip" Value="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=Content.Description}"/>
  48. </Trigger>
  49. </Style.Triggers>
  50. </Style>
  51. </ItemsControl.ItemContainerStyle>
  52. </ItemsControl>
  53. </Grid>
  54. </Window>

这里我们通过资源来引用一个类,让后使用  ItemsSource="{Binding Source={StaticResource myDataSource}}"将这个类绑定到ItemsSource控件上面,这里贴出相关的代码,我们定义了一个MyData的类,将该类作为数据源绑定到前台上,这个类的代码如下

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.ObjectModel;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7.  
  8. namespace TestGrid
  9. {
  10. public class MyData:ObservableCollection<DataSource>
  11. {
  12. public MyData()
  13. {
  14. Add (new DataSource()
  15. {
  16. Priority = "",
  17. TaskName = "My"
  18. }
  19. );
  20. Add(new DataSource()
  21. {
  22. Priority = "",
  23. TaskName = "Name"
  24. }
  25. );
  26. Add(new DataSource()
  27. {
  28. Priority = "",
  29. TaskName = "Is"
  30. }
  31. );
  32. Add(new DataSource()
  33. {
  34. Priority = "",
  35. TaskName = "Ye"
  36. }
  37. );
  38. Add(new DataSource()
  39. {
  40. Priority = "",
  41. TaskName = "Bo"
  42. }
  43. );
  44.  
  45. }
  46.  
  47. }
  48. }

这里面很重要的一部就是让这个类继承自 ObservableCollection<DataSource>,然后来添加相应的数据源,我们在使用继承的时候需要注意这些技巧。

其实这两种情况都是将一个数据集合绑定到前台,只不过是一些绑定的方式有所不同,实际的原理都是一样的!

ItemsControl的两种数据绑定方式的更多相关文章

  1. highcharts.js两种数据绑定方式和异步加载数据的使用

    一,我们先来看看异步加载数据的写法(这是使用MVC的例子) 1>js写法 <script src="~/Scripts/jquery-2.1.4.min.js"> ...

  2. Web APi之认证(Authentication)两种实现方式【二】(十三)

    前言 上一节我们详细讲解了认证及其基本信息,这一节我们通过两种不同方式来实现认证,并且分析如何合理的利用这两种方式,文中涉及到的基础知识,请参看上一篇文中,就不再叙述废话. 序言 对于所谓的认证说到底 ...

  3. Android中BroadcastReceiver的两种注册方式(静态和动态)详解

    今天我们一起来探讨下安卓中BroadcastReceiver组件以及详细分析下它的两种注册方式. BroadcastReceiver也就是"广播接收者"的意思,顾名思义,它就是用来 ...

  4. Android中Fragment与Activity之间的交互(两种实现方式)

    (未给Fragment的布局设置BackGound) 之前关于Android中Fragment的概念以及创建方式,我专门写了一篇博文<Android中Fragment的两种创建方式>,就如 ...

  5. JavaScript 函数的两种声明方式

    1.函数声明的方式 JavaScript声明函数有两种选择:函数声明法,表达式定义法. 函数声明法 function sum (num1 ,num2){ return num1+num2 } 表达式定 ...

  6. Redis两种持久化方式(RDB&AOF)

    爬虫和转载请注明原文地址;博客园蜗牛:http://www.cnblogs.com/tdws/p/5754706.html Redis所需内存 超过可用内存怎么办 Redis修改数据多线程并发—Red ...

  7. struts2+spring的两种整合方式

    也许有些人会因为学习了struts1,会以为struts2.struts1与spring的整合也是一样的,其实这两者相差甚远.下面就来讲解一下struts2与spring的整合两种方案.(部分转载,里 ...

  8. easyui datagride 两种查询方式

    easyui datagride 两种查询方式function doReseach() { //$('#tt').datagrid('load', { // FixedCompany: $('.c_s ...

  9. 【Visual Lisp】两种出错处理方式

    两种出错处理方式:一种是对出错函数进行重定义,一种是对错误进行捕捉处理. ;;============================================================= ...

随机推荐

  1. Cookie、sessionStorage与localStorage的区别

    (1) sessionStorage 保存数据的方法: SessionStor.setItem(“key”,”value”) 或者写成 sessionStorage.key=”value” 读取数据的 ...

  2. csvwrite

    https://ww2.mathworks.cn/help/matlab/ref/csvwrite.html

  3. jmeter(十八)关联之XPath Extractor

    之前的博客,有介绍jmeter如何对请求进行关联的一种常见用法,即:后置处理器中的正则表达式提取器,下面介绍另一种关联方法,XPath Extractor! 所谓关联,从业务角度讲,即:某些操作步骤与 ...

  4. (转)用graph-easy描绘kubenetes描绘k8s组件逻辑图

    1.参考: https://xuxinkun.github.io/2018/09/03/graph-easy/ http://bloodgate.com/perl/graph/manual/faq.h ...

  5. eaeyui-combobox实现组合查询(即实现多个值得搜索)

    2015年9月1日,今天要实现下拉框的组合查询功能,即可以再下拉框中选择多个值,输入框中每个值之间有逗号隔开,传到后台,由split函数将其分割开,组合成数组,在由sql查询. 实现的效果是: 当时在 ...

  6. Vue-详解设置路由导航的两种方法: <router-link :to="..."> 和router.push(...)

    一.<router-link :to="..."> to里的值可以是一个字符串路径,或者一个描述地址的对象.例如: // 字符串 <router-link to= ...

  7. 一个可爱 & 小清新的加载等待Android控件

    https://github.com/Carson-Ho/Kawaii_LoadingView

  8. LiveCharts文档-4基本绘图-1基本线条图

    原文:LiveCharts文档-4基本绘图-1基本线条图 4基本绘图-1基本线条图 using System; using System.Windows.Forms; using System.Win ...

  9. koa2入门(2) koa-router 路由处理

    项目地址:https://github.com/caochangkui/demo/tree/koa-test 1. 创建项目 创建目录 koa-test npm init 创建 package.jso ...

  10. dp方法论——由矩阵相乘问题学习dp解题思路

    前篇戳:dp入门——由分杆问题认识动态规划 导语 刷过一些算法题,就会十分珍惜“方法论”这种东西.Leetcode上只有题目.讨论和答案,没有方法论.往往答案看起来十分切中要害,但是从看题目到得到思路 ...