2012-07-13 60 views
1

使用DataTemplateSelector在運行時創建列。在XamlReader.Load處有異常:System.Windows.StaticResourceExtension。我如何加載資源?XamlReader.Load找不到靜態資源

var column = new DataGridTemplateColumn(); 
      column.Header = (i.Hour + 1).ToString(); 
      column.Width = 30; 
var parserContext = new ParserContext(); 
parserContext.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation"); 
parserContext.XmlnsDictionary.Add("x", "http://schemas.microsoft.com/winfx/2006/xaml"); 
parserContext.XmlnsDictionary.Add("local", "clr-namespace:ССПИ;assembly=ССПИ"); 
column.CellTemplateSelector = (DataTemplateSelector)XamlReader.Load(
       new MemoryStream(Encoding.Default.GetBytes(
        @"<local:ExtendedTemplateSelector TextBlockTemplate='{StaticResource TextBlockTemplate}' CheckBoxTemplate='{StaticResource CheckBoxTemplate}'/>" 
       )),parserContext);   
dataGrid1.Columns.Add(column); 

<DataGrid DataGridCell.Selected="DataGrid_GotFocus" EnableColumnVirtualization="true" EnableRowVirtualization="true" Name="dataGrid1" DockPanel.Dock="Top" AutoGenerateColumns="False" 
        Height="120" Width="Auto" CanUserReorderColumns="False" CanUserResizeColumns="False" CanUserAddRows="false" CanUserResizeRows="False" CanUserSortColumns="False" CellEditEnding="dataGrid1_CellEditEnding" ContextMenuOpening="dataGrid1_ContextMenuOpening"> 
        <DataGrid.Resources> 
         <DataTemplate x:Key="TextBlockTemplate"> 
          <TextBlock/> 
         </DataTemplate> 
         <DataTemplate x:Key="CheckBoxTemplate"> 
          <CheckBox IsChecked="False"/> 
         </DataTemplate> 
        </DataGrid.Resources> 

回答

0

在你的App.xaml:

<App.Resources> 
    <local:ExtendedTemplateSelector x:Key="MyExtendedTemplateSelector" TextBlockTemplate='{StaticResource TextBlockTemplate}' CheckBoxTemplate='{StaticResource CheckBoxTemplate}'/> 
</App.Resources> 

在你的.cs:

column.CellTemplateSelector = (DataTemplateSelector)((App)Application.Current)).Resources["MyExtendedTemplateSelector"]; 

據我所看到的,你不要在這裏需要一個解析器:它」只會讓事情變得複雜而慢一些。因此,只需將您的資源放在您的APP資源(或resourceDictionary中)中,並將其稱爲此類