Silverlight中的DataContext和ItemsSource 数据绑定

Silverlight中的DataContext和ItemsSource 数据绑定,第1张

概述 在Silverlight中我们经常看到数据绑定源由DataContext或者ItemsSource指定,那么他们之间的区别有哪些呢?     DataContext:从英文字母意思是数据上下文,在Silverlight中某个父级元素设置了DataContext,那么其子元素将可以继承并且使用DataContext中的属性。DataContext绑定的数据源可以是实体集合、实体、属性等。     

 在Silverlight中我们经常看到数据绑定源由DataContext或者ItemsSource指定,那么他们之间的区别有哪些呢?

    DataContext:从英文字母意思是数据上下文,在Silverlight中某个父级元素设置了DataContext,那么其子元素将可以继承并且使用DataContext中的属性。DataContext绑定的数据源可以是实体集合、实体、属性等。

    ItemsSource:其数据源通常是实体集合(多列数据),无法让其子元素继承使用。

    下面我们以一个实例主要讲解DataContext的用法,其中在父级元素GrID设置了一个DataContext属性绑定实体,该实体内部有一个属性为实体集合,此实体集合用于GrID的子元素ListBox的ItemsSource属性绑定。代码如下:

    首先我们看两个实体,其中一个实体属性为List<>:

    public class ClaModel    {        public ClaModel()        {            Claname = "五年级三班";            ClaInfo = 全校最好的班级,获得多项荣誉";            StuList = new List<StuModel>()            {                new StuModel(){Stuname=刘三",StuAge=15,StuInfo=他很勤奋"},李四14,0)">他很懒惰王五16,0)">他很聪明"}            };        }        string Claname { get; set; }        string ClaInfo { public List<StuModel> StuList { set; }    }    class StuModel    {        string Stuname { int StuAge { string StuInfo { set; }    }

    其次我们来看Xaml代码绑定如下:

<UserControl x:Class=SLDataContext.MainPage"    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:SLDataContext"    mc:Ignorable=d"    d:DesignHeight=300" d:DesignWIDth=400">    <!--第一种方式-->    <UserControl.Resources>        <local:ClaModel x:Key=ClaSource" />    </UserControl.Resources>    <GrID x:name=LayoutRoot" Background=White" DataContext={StaticResource ClaSource}">        <TextBlock FontWeight=Bold" WIDth=60" Height=30" Text={Binding Claname}"                    VerticalAlignment=top" HorizontalAlignment=left"   />        <TextBlock FontStyle=Italic"  WIDth=160{Binding ClaInfo}"                   VerticalAlignment=" margin=70 0 0 0"  />        <ListBox Height=239" name=lbDetail"                 VerticalAlignment=343" ItemsSource={Binding StuList}"                  SelectedValuePath=StuAge" displayMemberPath=Stuname27,61,0" />    </GrID></UserControl>

    最后我们看看另外一种后台绑定DataContext的方式。

partial class MainPage : UserControl { public MainPage() { InitializeComponent(); //第二种方式:也可以用后台代码绑定DataContext this.LayoutRoot.DataContext = new ClaModel(); } }

    如需源码请点击 SLDataContext.zip 下载 ,效果图如下:

      @H_389_301@

总结

以上是内存溢出为你收集整理的Silverlight中的DataContext和ItemsSource 数据绑定全部内容,希望文章能够帮你解决Silverlight中的DataContext和ItemsSource 数据绑定所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1068204.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-26
下一篇2022-05-26

发表评论

登录后才能评论

评论列表(0条)

    保存