开发者

Exception when setting the CellStyle property

In SL4 when setting the CellStyle for a DataGridTemplateColumn from code I get this exception:

MS.Internal.WrappedException: The type initializer for 'Missing template. Cannot initialize System.Windows.Controls.DataGridTemplateColumn.' threw an exception.

The code looks like this:

grdMain.IsReadOnly = true;   
DataGridTemplateColumn templateColumn = new DataGridTemplateColu开发者_JAVA百科mn();  templateColumn.HeaderStyle = (Style)this.Resources["ImageColumnHeaderStyle"]; 

templateColumn.CellStyle = (Style)this.Resources["CellStyle1"];  // This causes the exception   

//templateColumn.CellTemplate = (DataTemplate)this.Resources["DataTemplate1"];  // This works!      

grdMain.Columns.Add(templateColumn);

The markup is quite simple:

<Control.Resources>

   <Style x:Key="ImageColumnHeaderStyle" TargetType="sdk:DataGridColumnHeader">
    ...
   </Style>        

   <DataTemplate x:Key="DataTemplate1"> 
      <TextBlock>abcde</TextBlock>     
   </DataTemplate>       

  <Style x:Key="CellStyle1"  TargetType="sdk:DataGridCell"> 
   <Setter Property="Template" Value="{StaticResource DataTemplate1}">                 
</Setter>

  </Style>
</Control.Resources>

   <Grid x:Name="LayoutRoot">
       <sdk:DataGrid AutoGenerateColumns="False" Height="413" Name="grdMain" Width="335" />
   <Grid>

Since the style does nothing but setting the template to DataTemplate1, I am really puzzled!

Why does it work when I set the CellTemplate from code but not when I set it through the CellStyle property?

Thanks

//Peter


The Template property of any control takes a ControlTemplate not a DataTemplate as your code appears to be attempting. This:-

<Setter Property="Template" Value="{StaticResource DataTemplate1}" />

should be this:-

<Setter Property="ContentTemplate" Value="{StaticResource DataTemplate1}" />
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜