【问题标题】:Exception when setting the CellStyle property设置 CellStyle 属性时出现异常
【发布时间】:2011-04-19 19:13:41
【问题描述】:

在 SL4 中,当从代码中为 DataGridTemplateColumn 设置 CellStyle 时,我得到了这个异常:

MS.Internal.WrappedException:“缺少模板”的类型初始值设定项。无法初始化 System.Windows.Controls.DataGridTemplateColumn。'抛出异常。

代码如下所示:

grdMain.IsReadOnly = true;   
DataGridTemplateColumn templateColumn = new DataGridTemplateColumn();  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);

标记很简单:

<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>

由于样式只是将模板设置为DataTemplate1,我真的很困惑!

为什么当我从代码设置 CellTemplate 时它会起作用,而当我通过 CellStyle 属性设置它时它不起作用?

谢谢

//彼得

【问题讨论】:

  • 欢迎来到 SO,请花几分钟时间阅读常见问题解答和 Markdown 文档(编辑问题时右侧空白处提供了有用的概要)。
  • 它一定是 CellStyle1 声明中的东西,因为我已经尝试过你的代码并且它正在工作

标签: silverlight datagrid


【解决方案1】:

任何控件的Template 属性都采用ControlTemplate 而不是DataTemplate,因为您的代码似乎正在尝试。 这个:-

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

应该是这样的:-

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

【讨论】:

  • 差不多是 ContentTemplate(在 DataGridCell 上),而不是 CellTemplate(在 DataGridColumn 上)。
猜你喜欢
  • 2010-12-06
  • 2017-07-22
  • 1970-01-01
  • 2013-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-06
  • 1970-01-01
相关资源
最近更新 更多