在WPF中更改BitMapImage的尺寸,<Image>元素中可以放置哪些对象?

3
我正在尝试创建一个带有TreeView元素的资源管理器应用程序,并且每个树级别都有不同的图标。我遵循了这篇文章:http://www.codeproject.com/Articles/21248/A-Simple-WPF-Explorer-Tree,一切都运行良好,但是我还想拥有不同大小的图标。

我的Image元素XAML如下:

<Image Name="img"
       Source="{Binding RelativeSource={RelativeSource Mode=FindAncestor,
       AncestorType={x:Type TreeViewItem}},
       Path=Header,
       Converter={x:Static local:HeaderToImageConverter.Instance}}"
/>

决定返回哪个图标的代码如下:

if ((value as string).Contains(@"\""))
{
    Uri uri = new Uri ("pack://application:,,,/Images/DeployWiz_Network.png");
    BitmapImage source = new BitmapImage(uri);

    return source;
}

我该如何更改返回的图像尺寸?更改位图图像对象的尺寸似乎不起作用。还有哪些图像对象可以作为源返回?


1
为什么不直接设置“Image”控件的“Width”和“Height”呢? - Clemens
因为根据你所处的树的级别,我希望它是不同的。 - Dbloom
1个回答

16

好的,我想出了我的问题。哎呀,我真笨。以下是我更改的代码,它给我带来了想要的结果:

Uri uri = new Uri("pack://application:,,,/Images/DeployWiz_Network.png");
BitmapImage source = new BitmapImage();
source.BeginInit();
source.UriSource = uri;
source.DecodePixelHeight = 10;
source.DecodePixelWidth = 10;
source.EndInit();

return source;

5
不应同时设置DecodePixelWidthDecodePixelHeight,否则可能会破坏图像的长宽比。 - Clemens
1
@Dbloom:decodePixelHeight和Decodepixelwidth属性在Windows 8中不起作用,但在Windows 7和Windows 10中可以正常工作。 - secretgenes
2
较新版本的 BitmapImage 不再具有 BeginInit()EndInit() - Hendra Anggrian
澄清一下:截至net6(和net48),BeginInit()EndInit()仍然存在于BitmapImage中。 - b.pell

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接