DataTemplate总结1(学习)

有关DataBinding的心得

  1. DT作用于Content Control类控件与Items Control。
  2. 用到DT的property可以是ContentTemplate或者ItemTemplate。
  3. DT是某个控件的数据定制模板,一般给ItemControl的ItemTemplate属性使用。

 

项目截图和运行结果:


代码示例

 

//People.CS:

1
using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Collections.ObjectModel; //ObservableCollection的namespace 6 7 namespace TryItemTemplate 8 { 9 public class People 10 { 11 private string _name;    //定义Private 12 private string _photo; 13 14 public People(string name, string photo)   //定义People类的构造函数 15 { 16 this._name = name; 17 this._photo = photo; 18 } 19 public string Name 20 { 21 get { return this._name; } 22 set { this._name = value; } 23 } 24 public string Photo 25 { 26 get { return this._photo; } 27 set { this._photo = value; } 28 } 29 } 30 31 public class Peoples : ObservableCollection<People> //用来给ListBox传入一组值,其中ObservableCollection用来自动检测数值变化 32 { 33 public Peoples() : base() //定义Peoples类默认构造函数,并创建People类的两个实例 34 { 35 Add(new People("Chrysanthemum", @"C:\Users\Public\Pictures\Sample Pictures\Chrysanthemum.jpg")); 36 Add(new People("Desert", @"C:\Users\Public\Pictures\Sample Pictures\Desert.jpg")); 37 } 38 } 39 }

 

//MainMenu.xaml

<
Window x:Class="TryItemTemplate.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:TryItemTemplate" //引用上面C#进xaml        Title="MainWindow" Height="350" Width="525"> <Window.Resources> <local:Peoples x:Key="peopleListData"/> <!--引用后台Class People的数据,给个x:key--> <DataTemplate x:Key="myTemplate"> <Border Name="border" BorderBrush="Aqua" BorderThickness="2" Padding="5" Margin="5"> <Grid VerticalAlignment="Center" HorizontalAlignment="Center" Margin="4,4,4,4"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <Image Grid.Row="0" Width="50" Height="50" Source="{Binding Path=Photo}"/>  //由于ItemsSource指定了Source的来源,所以这里binding写path就好 <TextBlock Grid.Row="1" HorizontalAlignment="Center" VerticalAlignment="Center" Text="{Binding Path=Name}"/> </Grid> </Border> </DataTemplate> </Window.Resources> <StackPanel> <ListBox Width="400" Margin="10" ItemsSource="{Binding Source={StaticResource peopleListData}}" ItemTemplate="{StaticResource myTemplate}" HorizontalContentAlignment="Stretch" IsSynchronizedWithCurrentItem="True"/> <!--ItemsSource要用Binding Source={StaticResource}, ItemTemplate要用{StaticResource}--> </StackPanel> </Window>
posted @ 2012-08-30 08:15  若愚Shawn  阅读(318)  评论(0编辑  收藏  举报