c# - 如何从 xaml 中引用 .resx 文件中的图标?

标签 c# .net wpf data-binding icons

我正在开发一个 C# WPF 应用程序,使用 .resx 文件进行资源管理。现在,我正在尝试向项目添加图标 (.ico),但遇到了一些问题。

<Image Name="imgMin" Grid.Column="0"
       Stretch="UniformToFill"
       Cursor="Hand" 
       MouseDown="imgMin_MouseDown">
    <Image.Style>
        <Style TargetType="{x:Type Image}">
            <Setter Property="Source" Value="\Images\minimize_glow.ico"/>
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="Source" Value="\Images\minimize_glow.ico"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </Image.Style>
</Image>

这工作正常,但是当我将图标移动到 AppResources.resx 时,我遇到了在 xaml 代码中引用它的问题。我应该使用什么来代替上面的 Setter Property=... 行?这:

<Setter Property="Source" Value="{x:Static res:AppResources.minimize}"/>

不起作用,我想我可能需要使用与“源”不同的属性,因为现在值不是指向图标的字符串,而是图标本身。不过,我不知道该使用哪一个 - 请帮忙?

最佳答案

Source 属性并不“想要”一个字符串,它只是在获得一个字符串时对其进行转换。如果您将图标添加到资源中,它将是 System.Drawing.Icon 类型。您需要通过转换器将其转换为 ImageSource

您可以对资源进行静态访问,但它需要符合 x:Static 的预期语法。

例如

xmlns:prop="clr-namespace:Test.Properties"
<Image MaxHeight="100" MaxWidth="100">
    <Image.Source>
        <Binding Source="{x:Static prop:Resources.icon}">
            <Binding.Converter>
                <vc:IconToImageSourceConverter/>
            </Binding.Converter>
        </Binding>
    </Image.Source>
</Image>
public class IconToImageSourceConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        var icon = value as System.Drawing.Icon;
        var bitmap = icon.ToBitmap();

        //http://stackoverflow.com/questions/94456/load-a-wpf-bitmapimage-from-a-system-drawing-bitmap/1069509#1069509
        MemoryStream ms = new MemoryStream();
        bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
        ms.Position = 0;
        BitmapImage bi = new BitmapImage();
        bi.BeginInit();
        bi.StreamSource = ms;
        bi.EndInit();

        return bi;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

注意事项:

  • 资源访问修饰符必须是public
  • 如果将图像添加为“图像”,您最终会得到一个位图而不是一个图标,这需要不同的转换器

关于c# - 如何从 xaml 中引用 .resx 文件中的图标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5790617/

相关文章:

c# - 互锁和内存屏障

c# - IShellLinkW::GetPath( SLGP_RAWPATH ) 不返回 lnk 文件的 'raw' 目标

c# - 在 .NET 中更改代码中的 UserAgent

c# - 查找简单控制台 C# 程序消耗的内存

c# - 在 WPF 中重新加载绑定(bind)到 Datagrid 的 DataTable

wpf - 在 wpf 中的堆栈面板内平滑滚动

c# - 设备锁定或 sleep 时音频暂停 MonoTouch

c# - 使用 LINQ 表达式从 POCO 的 IEnumerable 中检索 IEnumerable 的属性

c# - MySQL-DBUpdateException ('Deadlock found when trying to get lock; try restarting transaction')

wpf - 在 Wpf 和 Xamarin Forms 之间共享 IValueConverter