WPF-DataTemplate创建数据模版

不得不说DataTemplate是WPF中的一项重要技术组成,可以方便让我们实现各种各样的UI样式,大大丰富了应用程序的界面设计。通常我们都会在XAML文件中定义出具体的DataTemplate, 我举一个ListView的例子:

 

 

<ListView IsSynchronizedWithCurrentItem="True" Background="#FFFFFFFF" 

 

Foreground="White" ItemsSource="{Binding}" Style="{DynamicResource

SuperListViewStyle}" ItemContainerStyleSelector="{StaticResource

listViewItemStyleSelector}" x:Name="lvExecutionTable" > <ListView.View> <GridView> <GridViewColumn> <GridViewColumn.CellTemplate> <DataTemplate> <CheckBox HorizontalAlignment="Center"

IsChecked="{Binding Path=IsSelected}"/> </DataTemplate> </GridViewColumn.CellTemplate> <GridViewColumnHeader Content="选择"

Tag="IsSelected"/> </GridViewColumn> <GridViewColumn> <GridViewColumn.CellTemplate> <DataTemplate> <TextBlock Text="{Binding

Path=IsComfirmed, Converter={StaticResource IsComfirmedConverter}}"

Foreground="{Binding Path=IsComfirmed, Converter={StaticResource

IsComfirmedToColorConverter}}"/> </DataTemplate> </GridViewColumn.CellTemplate> <GridViewColumnHeader Content="确认状态"

Tag="IsComfirmed"/> </GridViewColumn> <GridViewColumn DisplayMemberBinding="{Binding

Path=MarketIndicator}"> <GridViewColumnHeader Content="市场类型"

Tag="MarketIndicator"/> </GridViewColumn> <GridViewColumn> <GridViewColumn.CellTemplate> <DataTemplate> <TextBlock Text="{Binding

Path=TradeType}"/> </DataTemplate> </GridViewColumn.CellTemplate> <GridViewColumnHeader Content="成交方式"

Tag="TradeType"/> </GridViewColumn> </GridView> </ListView.View> </ListView>

 

 

例子中对每个Column定义了简单的DataTemplate。我遇到的问题是如果这个List View需要动态编辑列,或者新加入一些列,就是如何用代码来实现对控件的DataTemplate的操作。经过查阅MSDN的相关文档,最好找到了解决的办法,如下:

GridViewColumn column = new GridViewColumn();
GridViewColumnHeader h = new GridViewColumnHeader();
h.Content = "??????";
h.Tag = "*******";
column.Header = h;
DataTemplate dt = new DataTemplate();
FrameworkElementFactory fef = new FrameworkElementFactory(typeof

 

(CheckBox)); Binding binding = new Binding(); binding.Path = new PropertyPath("MarketIndicator"); fef.SetBinding(CheckBox.ContentProperty, binding); fef.SetValue(CheckBox.ForegroundProperty, Brushes.White); dt.VisualTree = fef; column.CellTemplate = dt;

(this.lvExecutionTable.View as GridView).Columns.Add(column);

DataTemplate对象的VisualTree属性的类型是FrameworkElementFactory,用来存放具体的Control。FrameworkElementFactory fef = new FrameworkElementFactory(typeof(CheckBox))语句定义了DataTemplate的顶层元素是一个CheckBox控件,使用fef.SetValue方法可以设置顶层元素的属性,如绑定等等。如果你需要定义的DataTemplate不止一个层次,那么你就要花点时间去设置顶层元素的Content属性。

你可能感兴趣的:(WPF-DataTemplate创建数据模版)