WPF之DataTemplate

DataTemplate顾名思义,就是数据模板,用来指定数据的表现形式。这对于ItemsControl类的控件尤其有用,可以改变列表项的外观,更具有表现能力。

例如

<Grid>
<Grid.Resources>
<src:Customers x:Key="customers"/>
</Grid.Resources>

<ListBox ItemsSource="{StaticResource customers}" Width="350" Margin="0,5,0,10">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Padding="5,0,5,0"
Text="{Binding FirstName}" />
<TextBlock Text="{Binding LastName}" />
<TextBlock Text=", " />
<TextBlock Text="{Binding Address}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>

<Grid><Grid.Resources><src:Customers x:Key="customers"/></Grid.Resources><ListBox ItemsSource="{StaticResource customers}" Width="350" Margin="0,5,0,10"><ListBox.ItemTemplate><DataTemplate><StackPanel Orientation="Horizontal"><TextBlock Padding="5,0,5,0"Text="{Binding FirstName}" /><TextBlock Text="{Binding LastName}" /><TextBlock Text=", " /><TextBlock Text="{Binding Address}" /></StackPanel></DataTemplate></ListBox.ItemTemplate></ListBox>
</Grid>

上例中通过指定ListBox.ItemTemplate属性来定义子项的显示格式,如果不是列表项,可以通过控件的ContentTemplate属性来指定应用哪个数据模板。

使用起来比较简单,大概分为三步:

1.如果有些属性不是可以直接使用,需要转换的,写转换器,实现IValueConverter接口

2.定义好转换器之后,需要实例化,指定给需要的绑定

3.定义模板,也就是需要的显示格式

4.应用模板,把定义好的模板指定到目标控件的ContentTemplate或者ItemTemplate

看一个完整的例子

1.用来封装的实体类和转换器

class Car
{
public string Automaker { get; set; }
public string Name { get; set; }
public string Year { get; set; }
public string TopSpeed { get; set; }
}

//厂商名称转化为Logo图片
public class AutomakerToLogoPathConverter:IValueConverter
{

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string uriStr = string.Format(@"images/{0}.jpg",value.ToString());
return new BitmapImage(new Uri(uriStr, UriKind.Relative));
}

public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}

//汽车名称转化为图像
public class NameToPhotoPathConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string uriStr = string.Format(@"images/{0}.jpg", value.ToString());
return new BitmapImage(new Uri(uriStr, UriKind.Relative));
}

public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}

class Car{public string Automaker { get; set; }public string Name { get; set; }public string Year { get; set; }public string TopSpeed { get; set; }}//厂商名称转化为Logo图片public class AutomakerToLogoPathConverter:IValueConverter{public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture){string uriStr = string.Format(@"images/{0}.jpg",value.ToString());return new BitmapImage(new Uri(uriStr, UriKind.Relative));}public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture){throw new NotImplementedException();}}//汽车名称转化为图像public class NameToPhotoPathConverter : IValueConverter{public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture){string uriStr = string.Format(@"images/{0}.jpg", value.ToString());return new BitmapImage(new Uri(uriStr, UriKind.Relative));}public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture){throw new NotImplementedException();}}

2.模板及窗体

<Window x:Class="TempaletPractise.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TempaletPractise"
Title="汽车展览" Height="350" Width="623">
<Window.Resources>
<!--Converter-->
<local:AutomakerToLogoPathConverter x:Key="a2l"></local:AutomakerToLogoPathConverter>
<local:NameToPhotoPathConverter x:Key="n2p"></local:NameToPhotoPathConverter>

<!--Data Template for Detail View-->
<DataTemplate x:Key="carDetailViewTemplate">
<Border BorderBrush="Black" BorderThickness="1" CornerRadius="6">
<StackPanel Margin="5">
<Image Width="400" Height="250" Source="{Binding Name, Converter={StaticResource n2p}}"></Image>
<StackPanel Orientation="Horizontal" Margin="5,0">
<TextBlock Text="Name:" FontWeight="Bold" FontSize="20"></TextBlock>
<TextBlock Text="{Binding Name}" FontSize="20" Margin="5,0"></TextBlock>
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="5,0">
<TextBlock Text="Automaker" FontWeight="Bold"></TextBlock>
<TextBlock Text="{Binding Automaker}" Margin="5,0"></TextBlock>
<TextBlock Text="Year" FontWeight="Bold"></TextBlock>
<TextBlock Text="{Binding Year}" Margin="5,0"></TextBlock>
<TextBlock Text="Top Speed" FontWeight="Bold"></TextBlock>
<TextBlock Text="{Binding TopSpeed}" Margin="5,0"></TextBlock>
</StackPanel>
</StackPanel>
</Border>
</DataTemplate>

<!--DataTemplate for Item View-->
<DataTemplate x:Key="carListItemViewTemplate">
<Grid Margin="2">
<StackPanel Orientation="Horizontal">
<Image Source="{Binding Automaker,Converter={StaticResource a2l}}"
Grid.RowSpan="3" Width="64" Height="64"></Image>
<StackPanel Margin="5,0">
<TextBlock Text="{Binding Name}" FontSize="16" FontWeight="Bold"></TextBlock>
<TextBlock Text="{Binding Year}" FontSize="14"></TextBlock>
</StackPanel>
</StackPanel>
</Grid>
</DataTemplate>
</Window.Resources>
<!--窗体的内容-->
<StackPanel Orientation="Horizontal" Margin="5">
<UserControl ContentTemplate="{StaticResource carDetailViewTemplate}"
Content="{Binding SelectedItem, ElementName=listBoxCars}"></UserControl>
<ListBox x:Name="listBoxCars" Width="180" Margin="5,0" ItemTemplate="{StaticResource carListItemViewTemplate}"></ListBox>
</StackPanel>
</Window>

3.指定数据源

private void InitialCarList()
{
List<Car> cars = new List<Car>()
{
new Car(){ Automaker="CADILLAC",Name="CADILLAC1",Year="1990",TopSpeed="340"},
new Car(){ Automaker="Ferrari",Name="Ferrari1",Year="1991",TopSpeed="350"},
new Car(){ Automaker="LAMBORGHINI",Name="LAMBORGHINI1",Year="1992",TopSpeed="360"},
new Car(){ Automaker="PORSCHE",Name="PORSCHE1",Year="1993",TopSpeed="370"}
};

this.listBoxCars.ItemsSource = cars;
}

参考 MSDN 《深入浅出WPF》第11章

ps.今天看到园子编辑推荐的一则新闻,Silverlight开始边缘化,从官方就开始不推了,不知道WPF的命运会怎样,在微软的大船上,只能跟着起伏,不过今天能从ASP.NET转WPF,明天也能从WPF转其他技术,我们从来就不怕这个,毕竟我们学过,想过,用过,他帮助过我们,每种技术都代表了一种思想,技术可以没落,思想却沉淀下来了。

转载于:https://www.cnblogs.com/LiZhongZhongY/p/10896691.html

WPF之DataTemplate(转)相关推荐

  1. WPF 用 DataTemplate 合并DataGrid列表列头类似报表设计及行头列头样式 - 学习

    WPF中 DataGrid 列头合并,类似于报表设计.效果图如下↓ 1.新建一个WPF项目WpfApplication1,新建一个窗体DataGridTest,前台代码如下: <Window x ...

  2. WPF 在DataTemplate中使用DataType

    DataTemplate中的DataType的功能实际上和Style中的TargetType很类似. 在Style中,使用了TargetType之后,如果不定义Style的Key,那么这个Style将 ...

  3. 分享Silverlight/WPF/Windows Phone一周学习导读(4月4日-4月9日)

    期待已久的Silverlight 5即将到来,上周不少关于MIX11的话题,其中值得关注的有以下几篇: MIX11: Silverlight 5,Windows Phone,IE9,HTML5及直播预 ...

  4. 分享Silverlight/WPF/Windows Phone/HTML5一周学习导读(12月12日-12月18日)

    分享Silverlight/WPF/Windows Phone/HTML5一周学习导读(12月12日-12月18日) 本周Silverlight学习资源更新 Silverlight学习小记 阿里山地方 ...

  5. 分享Silverlight/WPF/Windows Phone一周学习导读(06月06日-06月11日)

    Windows 8预览版推出后,Silverlight社区掀起一番新的"Silverlight灭亡"讨论,由于Windows 8预览版中微软重点强调HTML 5和Javascrip ...

  6. 分享Silverlight/WPF/Windows Phone一周学习导读(8月28日-9月3日)

    分享Silverlight/WPF/Windows Phone一周学习导读(8月28日-9月3日) 本周Silverlight学习资源更新: Silverlight动画 cutylongshen Si ...

  7. css hover变成手_html实现鼠标悬停变成手型实现方式

    1.采用a标签实现的方式 内容 2.采用CSS实现的方式 // 变手形 oElement.style.cursor = "pointer"; // 恢复原样 oElement.st ...

  8. WPF中ControlTemplate和DataTemplate的区别

    原文:WPF中ControlTemplate和DataTemplate的区别 下面代码很好的解释了它们之间的区别: <Window x:Class="WPFTestMe.Window1 ...

  9. WPF Template模版之DataTemplate与ControlTemplate的关系和应用【二】

    1. DataTemplate和ControlTemplate的关系 学习过DataTemplate和ControlTemplate,你应该已经体会到,控件只是数据的行为和载体,是个抽象的概念,至于它 ...

最新文章

  1. jquery的基本api
  2. Caused by: java.lang.ClassNotFoundException: Didn't find class android.support.v4.view.ViewPager
  3. 智能胖墩机器人_探班新雅CDIE | 智能硬件“奇幻乐园”
  4. SAP Commerce Cloud SmartEdit 学习笔记
  5. 数据科学 IPython 笔记本 8.3 Matplotlib 可视化
  6. matlab 可视化 —— imagesc、
  7. 网络管理之TCP/UDP篇
  8. scrollView截取指定区域的图片
  9. 大数据应用及其解决方案(完整版)
  10. MSAgent 详细解说(下)
  11. 开源项目之Windows读取Ext4分区的工具 Ext2Read
  12. AI之语音转写项目实践
  13. 贾俊平统计学思维导图- 第八章 假设检验
  14. linux下好用的中文输入法
  15. can总线短距离不用双绞线_CAN总线布线规范
  16. 利用ettercap进行简单的arp欺骗和mitm攻击
  17. docker容器内启动mysql服务,报错:New main PID 99 does not belong to service, and PID file is not owned by root.
  18. 史上ElasticSearch 最全详细使用教程
  19. android仿网易云音乐引导页、仿书旗小说Flutter版、ViewPager切换、风扇叶片效果等源码...
  20. 【论文阅读】TomoAlign: A novel approach to correcting sample motion and 3D CTF in CryoET

热门文章

  1. php server phpself,nginx中的PATH_INFO为什么会影响$_SERVIER['PHP_SELF']
  2. php get 分页,PHP_codeigniter实现get分页的方法,本文实例讲述了codeigniter实现ge - phpStudy...
  3. 什么叫内部银团_什么样的户型是好户型
  4. pcb二次钻孔_作为一名合格的PCB设计工程师,了解生产制造很重要
  5. pytorch 创建神经网络
  6. pytorch nn.Conv1d
  7. 09 动态数组和数据
  8. 2.6 谷歌 Inception 网络简介
  9. Matplotlib Line2D设置
  10. tp5写的系统比php源码写的慢多少,基于TP5框架开发的极速企业网站开发框架PHP源码...