【问题标题】:Setting Image in code behind is not showing up in wpf datagrid column在后面的代码中设置图像未显示在 wpf datagrid 列中
【发布时间】:2011-07-18 10:29:28
【问题描述】:

我有一个数据模板来在数据网格列中显示图标。我在后面的代码中设置了图像源。但不知何故,图像在运行时没有出现在网格中。我错过了什么吗??

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

【问题讨论】:

  • 我认为这是因为 StaticResource...StaticResource 是可冻结的对象。所有静态资源都在加载或初始化时解析,并且在运行时所做的更改不会显示任何效果...尝试执行与 DynamicResources 相同...
  • 以某种方式设置 DynamicResource 也不起作用

标签: c# .net wpf xaml wpfdatagrid


【解决方案1】:

LoadContent 不会在这里提供帮助:

将模板的内容作为对象的实例加载并返回内容的根元素。

返回值

类型:System.Windows.DependencyObject
内容的根元素。多次调用它会返回单独的实例。

此外,您不能修改 DataTemplate,因为它们一旦使用就会被密封。您可以将 DataTemplate 作为 DynamicResource 引用,并在运行时完全替换旧模板。

【讨论】:

    猜你喜欢
    • 2011-10-29
    • 2012-04-01
    • 1970-01-01
    • 2021-06-12
    • 1970-01-01
    • 2012-01-05
    • 1970-01-01
    • 1970-01-01
    • 2021-10-12
    相关资源
    最近更新 更多