ItemsControl的两种数据绑定方式

简介: 原文:ItemsControl的两种数据绑定方式     最近在学习ItemsControl这个控件的时候,查看了MSDN上面的一个例子,并且自己做了一些修改,这里主要使用了两种方式来进行相应的数据绑定,一种是使用DataContext,另外一种是直接将一个类绑定到前台,其实这两种方式原理差不多都...
原文: ItemsControl的两种数据绑定方式

     最近在学习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="350" Width="525">    
    <Grid>
        <ItemsControl Margin="10" x:Name="myItemsControl"  ItemsSource="{Binding}">          
            <ItemsControl.Template>
                <ControlTemplate TargetType="ItemsControl">
                    <Border BorderBrush="Aqua" BorderThickness="1" CornerRadius="15">
                        <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="18"/>
                            <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="100"/>
                    <Setter Property="Control.Margin" Value="5"/>
                    <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 = "1",
                    TaskName = "hello"
                }
                );
            item.Add(
                 new DataSource()
                {
                    Priority = "2",
                    TaskName = "whats"
                }
                );
            item.Add(
                new DataSource()
                {
                    Priority = "3",
                    TaskName = "your"
                }
               );
            item.Add(
                new DataSource()
                {
                    Priority = "4",
                    TaskName = "name"
                }
               );
            item.Add(
                new DataSource()
                {
                    Priority = "5",
                    TaskName = "can"
                }
               );
            item.Add(
                new DataSource()
                {
                    Priority = "6",
                    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="350" Width="525">
    <Window.Resources>
        <local:MyData x:Key="myDataSource"/>
    </Window.Resources>
    <Grid>
        <ItemsControl Margin="10" x:Name="myItemsControl"  ItemsSource="{Binding Source={StaticResource myDataSource}}">          
            <ItemsControl.Template>
                <ControlTemplate TargetType="ItemsControl">
                    <Border BorderBrush="Aqua" BorderThickness="1" CornerRadius="15">
                        <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="18"/>
                            <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="100"/>
                    <Setter Property="Control.Margin" Value="5"/>
                    <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 = "1",
                    TaskName = "My"
                }
                );
           Add(new DataSource()
               {
                   Priority = "2",
                   TaskName = "Name"
               }
                );
           Add(new DataSource()
               {
                   Priority = "3",
                   TaskName = "Is"
               }
                );
           Add(new DataSource()
               {
                   Priority = "4",
                   TaskName = "Ye"
               }
                );
           Add(new DataSource()
               {
                   Priority = "5",
                   TaskName = "Bo"
               }
                );
       
       }
       
    }
}

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

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

目录
相关文章
|
C# 图形学 Windows
Winform控件优化之背景透明那些事2:窗体背景透明、镂空穿透、SetStyle、GDI透明效果等
两行代码就能实现Form窗体的(背景)透明效果,它不是Opacity属性的整个窗体透明,`TransparencyKey`实现窗体的透明、窗体中间部分镂空效果...
4063 0
Winform控件优化之背景透明那些事2:窗体背景透明、镂空穿透、SetStyle、GDI透明效果等
|
C# 前端开发
WPF DatePicker默认显示当前日期,格式化为年月日
原文:WPF DatePicker默认显示当前日期 WPF的日历选择控件默认为当前日期,共有两种方法,一种静态,一种动态。 静态的当然写在DatePicker控件的属性里了,动态的写在对应的cs文件里,具体请看下面。
6775 0
|
10月前
|
存储 监控 数据可视化
双十一线上服务调用链路追踪SkyWalking实战分析
【11月更文挑战第27天】随着电商行业的飞速发展,双十一购物节已成为全球最大的购物狂欢节之一。在双十一期间,电商平台需要处理海量的用户请求和订单,这对系统的稳定性和性能提出了极高的要求。为了确保系统在高并发环境下的稳定运行,对线上服务的调用链路进行追踪和分析显得尤为重要。本文将通过实战案例,详细介绍如何在双十一期间使用SkyWalking对线上服务进行调用链路追踪,并结合Seata实现分布式事务管理,从而保障系统的稳定性和性能。
309 6
|
10月前
|
数据处理 C# Windows
WPF中实现弹出进度条窗口
【11月更文挑战第14天】在WPF中实现弹出进度条窗口,需创建进度条窗口界面(XAML)和对应的代码-behind(C#)。通过定义`ProgressWindow`类,包含`ProgressBar`和`TextBlock`,并在主窗口或逻辑代码中调用,模拟长时间任务时更新进度条,确保UI流畅。
420 0
|
设计模式 前端开发 数据可视化
LiveCharts2:简单灵活交互式且功能强大的.NET图表库
LiveCharts2:简单灵活交互式且功能强大的.NET图表库
478 0
|
搜索推荐 物联网 API
探索iOS应用开发的新趋势
【6月更文挑战第19天】在移动技术不断进步的今天,iOS应用开发正面临前所未有的变革。本文将深入探讨最新的iOS开发技术,包括SwiftUI框架的创新使用、Combine框架在数据处理中的优势,以及App Clips和WidgetKit如何为应用带来新的生机。通过分析这些技术的实际应用案例,我们旨在为开发者提供一条清晰的道路,帮助他们把握未来iOS应用的开发方向。
|
移动开发 小程序 API
uniapp组件库SwipeAction 滑动操作 使用方法
uniapp组件库SwipeAction 滑动操作 使用方法
566 1
|
开发框架 前端开发 .NET
Visual Studio中的四款代码格式化工具
Visual Studio中的四款代码格式化工具
521 0
|
缓存 人工智能 定位技术
探究Qt Quick之Overlay类的魅力(二)
探究Qt Quick之Overlay类的魅力
255 0
|
运维 安全 Linux
如何在Linux部署JumpServer堡垒机并实现远程访问本地服务
如何在Linux部署JumpServer堡垒机并实现远程访问本地服务
442 0