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

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

<Window x:Class="TestGrid.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TestGrid"
Title="MainWindow" Height="" Width="">
<Grid>
<ItemsControl Margin="" x:Name="myItemsControl" ItemsSource="{Binding}">
<ItemsControl.Template>
<ControlTemplate TargetType="ItemsControl">
<Border BorderBrush="Aqua" BorderThickness="" CornerRadius="">
<ItemsPresenter/>
</Border>
</ControlTemplate>
</ItemsControl.Template>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{ x:Type local:DataSource}">
<DataTemplate.Resources>
<Style TargetType="TextBlock">
<Setter Property="FontSize" Value=""/>
<Setter Property="HorizontalAlignment" Value="Center"/>
</Style>
</DataTemplate.Resources>
<Grid>
<Rectangle Fill="Green"/>
<Ellipse Fill="Red"/>
<StackPanel>
<TextBlock Margin="3,3,3,0" Text="{Binding Path=Priority,Mode=TwoWay}"/>
<TextBlock Margin="3,0,3,7" Text="{Binding Path=TaskName,Mode=TwoWay}"/>
</StackPanel>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemContainerStyle>
<Style>
<Setter Property="Control.Width" Value=""/>
<Setter Property="Control.Margin" Value=""/>
<Style.Triggers>
<Trigger Property="Control.IsMouseOver" Value="True">
<Setter Property="Control.ToolTip" Value="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=Content.Description}"/>
</Trigger>
</Style.Triggers>
</Style>
</ItemsControl.ItemContainerStyle>
</ItemsControl>
</Grid>
</Window>

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

using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes; namespace TestGrid
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
private ObservableCollection<DataSource> item = null;
public MainWindow()
{
InitializeComponent();
item = new ObservableCollection<DataSource>();
item.Add(
new DataSource()
{
Priority = "",
TaskName = "hello"
}
);
item.Add(
new DataSource()
{
Priority = "",
TaskName = "whats"
}
);
item.Add(
new DataSource()
{
Priority = "",
TaskName = "your"
}
);
item.Add(
new DataSource()
{
Priority = "",
TaskName = "name"
}
);
item.Add(
new DataSource()
{
Priority = "",
TaskName = "can"
}
);
item.Add(
new DataSource()
{
Priority = "",
TaskName = "you"
}
);
this.myItemsControl.DataContext = item; }
}
}
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace TestGrid
{
public class DataSource : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public DataSource()
{
} private string priority;
public string Priority
{
get
{
return priority;
}
set
{
priority = value;
OnPropertyChanged("Priority");
}
} private string taskname;
public string TaskName
{
get
{
return taskname;
}
set
{
taskname = value;
OnPropertyChanged("TaskName");
}
} protected void OnPropertyChanged(string propName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propName));
} } private List<DataSource> datasources; public List<DataSource> DataSources
{
get { return datasources; }
set { datasources = value; }
} }
}

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

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

<Window x:Class="TestGrid.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TestGrid"
Title="MainWindow" Height="" Width="">
<Window.Resources>
<local:MyData x:Key="myDataSource"/>
</Window.Resources>
<Grid>
<ItemsControl Margin="" x:Name="myItemsControl" ItemsSource="{Binding Source={StaticResource myDataSource}}">
<ItemsControl.Template>
<ControlTemplate TargetType="ItemsControl">
<Border BorderBrush="Aqua" BorderThickness="" CornerRadius="">
<ItemsPresenter/>
</Border>
</ControlTemplate>
</ItemsControl.Template>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{ x:Type local:DataSource}">
<DataTemplate.Resources>
<Style TargetType="TextBlock">
<Setter Property="FontSize" Value=""/>
<Setter Property="HorizontalAlignment" Value="Center"/>
</Style>
</DataTemplate.Resources>
<Grid>
<Rectangle Fill="Green"/>
<Ellipse Fill="Red"/>
<StackPanel>
<TextBlock Margin="3,3,3,0" Text="{Binding Path=Priority,Mode=TwoWay}"/>
<TextBlock Margin="3,0,3,7" Text="{Binding Path=TaskName,Mode=TwoWay}"/>
</StackPanel>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemContainerStyle>
<Style>
<Setter Property="Control.Width" Value=""/>
<Setter Property="Control.Margin" Value=""/>
<Style.Triggers>
<Trigger Property="Control.IsMouseOver" Value="True">
<Setter Property="Control.ToolTip" Value="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=Content.Description}"/>
</Trigger>
</Style.Triggers>
</Style>
</ItemsControl.ItemContainerStyle>
</ItemsControl>
</Grid>
</Window>

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

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace TestGrid
{
public class MyData:ObservableCollection<DataSource>
{
public MyData()
{
Add (new DataSource()
{
Priority = "",
TaskName = "My"
}
);
Add(new DataSource()
{
Priority = "",
TaskName = "Name"
}
);
Add(new DataSource()
{
Priority = "",
TaskName = "Is"
}
);
Add(new DataSource()
{
Priority = "",
TaskName = "Ye"
}
);
Add(new DataSource()
{
Priority = "",
TaskName = "Bo"
}
); } }
}

这里面很重要的一部就是让这个类继承自 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. Mybatis集成(转)

    文章转自http://blog.csdn.net/l454822901/article/details/51829653 什么是Mybatis MyBatis 本是apache的一个开源项目iBati ...

  2. Java内存区域划分、内存分配原理(转)

    文章引用自 http://blog.csdn.net/OyangYujun/article/details/41173747 运行时数据区域 Java虚拟机在执行Java的过程中会把管理的内存划分为若 ...

  3. Mysql数据库的加密与解密

    数据加密.解密在安全领域非常重要.对程序员而言,在数据库中以密文方式存储用户密码对入侵者剽窃用户隐私意义重大. 有多种前端加密算法可用于数据加密.解密,下面我向您推荐一种简单的数据库级别的数据加密.解 ...

  4. 使用systemctl报错(centos 7)

    服务器运行210多天,今天使用systemctl准备重启下sshd发现报错,如上图. systemctl restart.stop.status.start等所有操作都报错.原因未知. 在此之前有内存 ...

  5. [Spark][Python]spark 从 avro 文件获取 Dataframe 的例子

    [Spark][Python]spark 从 avro 文件获取 Dataframe 的例子 从如下地址获取文件: https://github.com/databricks/spark-avro/r ...

  6. linux中fork, source和exec的区别

    转:linux中fork, source和exec的区别 shell的命令可以分为内部命令和外部命令. 内部命令是由特殊的文件格式.def实现的,如cd,ls等.而外部命令是通过系统调用或独立程序实现 ...

  7. 【已解决】在 Visual Studio 中设置 JavaScript/TypeScript 的断点 脚本出现自动中断错误

    运行ASP.NET Core 程序出现错误如下: 已启用 Visual Studio 中的 Chrome 脚本调试 在 Visual Studio 中设置 JavaScript/TypeScript ...

  8. VS2017登陆不了,TFS无法连接成功的问题

    由于使用的win7 64位操作系统,重装系统以后,安装了vs2017,登陆不成功,https://auth.gfx.ms/16.000.27887.2/OldConvergedLogin_PCore. ...

  9. vs2017安装

    每次安装包都搞的很大,而且出各式各式的问题. 安装程序清单签名失败 运行'vs_Enterprise.exe'时,出现'安装程序清单签名失败'的错误,直接删除'vs_installer.opc'文件, ...

  10. Python_命名空间和作用域_25

    # 函数进阶 a = def func(): print(a) func() # 命名空间和作用域 # print() # input() # list # #命名空间 有三种 #内置命名空间 —— ...