最近在学习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. day04流程控制之while

    while语法: while 条件:  缩进的循环体 # 如果条件为真,那么循环体则执行,执行完毕后再次循环,重新判断条件. # 如果条件为假,那么循环体不执行,循环终止 示例一: "&qu ...

  2. Python将数据渲染到docx文档指定位置

    超简单Python将指定数据插入到docx模板渲染并生成 最近有一个需求,制作劳动合同表,要从excel表格中将每个人的数据导入到docx劳动合同中,重复量很大,因此可以使用python高效解决.为了 ...

  3. Objective-C autoreleasepool深入理解

    Objective-C autorelease // main.m int main(int argc, char * argv[]) { @autoreleasepool { } } clang - ...

  4. 【Codeforces 499D】Name That Tune

    Codeforces 499 D 题意:给\(n\)个曲子,每个曲子每一秒有\(p_i\)的几率可以被猜出来,过了\(t_i\)秒肯定能被猜出来,猜完第\(i\)首歌立即播第\(i+1\)首,问\(T ...

  5. 在Oracle中执行动态SQL的几种方法

    转载:在Oracle中执行动态SQL的几种方法 以下为内容留存: 在Oracle中执行动态SQL的几种方法 在一般的sql操作中,sql语句基本上都是固定的,如:SELECT t.empno,t.en ...

  6. apache、nginx的虚拟域名配置和rewrite配置,以及web缓存的几种方式

    web缓存一般用来缓解数据库压力. 通常有几种方法,文件静态化,缓存服务memcached.redis等. 伪静态,一般指在url上貌似访问静态html页的形式,这样有利于搜索引擎访问到网站页面,实际 ...

  7. python中的 sql语句用法

    函数中应用sql语句def _get_cust_number(self,cr,uid,ids,field_name,args,context=None): res={} for order in se ...

  8. Matplotlib 简单图例

    图例参考:http://matplotlib.org/gallery.html API参考:http://matplotlib.org/api/pyplot_summary.html # -*- co ...

  9. CF1039E Summer Oenothera Exhibition 贪心、根号分治、倍增、ST表

    传送门 感谢这一篇博客的指导(Orzwxh) $PS$:默认数组下标为$1$到$N$ 首先很明显的贪心:每一次都选择尽可能长的区间 不妨设$d_i$表示在取当前$K$的情况下,左端点为$i$的所有满足 ...

  10. Luogu4139 上帝与集合的正确用法 拓展欧拉定理

    传送门 题意:求$2^{2^{2^{2^{...}}}} \mod p$的值.$p \leq 10^7$ 最开始想到的是$x \equiv x^2 \mod p$,然后发现不会做... 我们可以想到拓 ...