我有一个数据模板,用于在datagrid列中显示图标。我在后面的代码中设置了图像源。但不知何故,图像在运行时没有出现在网格中。我错过了什么吗?
<DataTemplate x:Key="iconTemplate">
<Image/>
</DataTemplate>
背后的代码
var cellTemplate = (DataTemplate)Resources["iconTemplate"];
var image = cellTemplate.LoadContent() as Image;
image.Source = new BitmapImage(new Uri(@"C:\images\16x16\image.png"));
column.CellTemplate = cellTemplate;
在xaml中设置datagrid模板列的单元格模板。
<DataGrid.Columns>
<DataGridTemplateColumn Header="Comments" CellTemplate="{StaticResource iconTemplate}"/>
</DataGrid.Columns>
答案 0 :(得分:1)
LoadContent
在这里没有帮助:
将模板的内容作为对象的实例加载,并返回内容的根元素。
返回值
类型:System.Windows.DependencyObject
内容的根元素。多次调用会返回不同的实例。
此外,您无法修改DataTemplates,因为它们在使用后会被密封。您可以将DataTemplate作为DynamicResource引用,并在运行时完全替换旧模板。