【发布时间】: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