我有一个 WPF 应用程序,我在其中使用了几个图像。大多数图像都在 XAML 代码中设置,因为它们不会再更改。我的Build Action
所有图像文件都设置为"Resource"并且Copy to Output Directory
设置为"Do Not Copy"。它们按预期显示,以下是如何设置它们的示例:
<ribbon:RibbonApplicationMenu SmallImageSource="/Voetbal;component/Images/Ball_16.png">
//or
<ribbon:RibbonButton LargeImageSource="/Voetbal;component/Images/Calendar_32.png" />
//or
<Image Source="/Voetbal;component/Images/remove.png" Width="16" Height="16" />
但我也有必须通过 C# 设置的图像。在用户控件中,我有一个 ListView,其中包含带有以下标记的特定列:
<GridViewColumn Header="" Width="32">
<GridViewColumn.CellTemplate>
<DataTemplate>
<Image Source="{Binding Icon}" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
ListView 的 ItemsSource 是一个通用列表,其中包含将填充 ListView 的项的实例。这些项目有两个字符串字段和一个 ImageSource(名为“Icon”)。我像这样设置图标属性:
var icon = new BitmapImage(new Uri("/Images/Gold_16.png", UriKind.RelativeOrAbsolute));
myViewModel.Items[0].Icon = icon;
但问题是我在 ListView 中看不到图像。我也尝试过以下代码。我在 SO 和其他论坛上使用了这些来自类似问题的答案的文章。不是我一直懒惰或没有尝试任何东西,而是我不知道如何解决这个问题......
var icon = new BitmapImage(new Uri("/Voetbal;component/Images/Gold_16.png", UriKind.RelativeOrAbsolute));
//or
var icon = new BitmapImage();
icon.BeginInit();
icon.UriSource = new Uri("pack://application:,,,/Voetbal;component/Images/Gold_16.png");
icon.EndInit();
//or
var icon = new BitmapImage();
icon.BeginInit();
icon.UriSource = new Uri("pack://application:,,,/Images/Gold_16.png");
icon.EndInit();
PS:我知道我的 ViewModel 的绑定有效,因为这两个字符串属性正确显示在 ListView 的其他列中。
有谁知道我如何设置 ImageSource 并将其正确绑定到 ListView?
提前致谢!