不得不說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屬性。