在窗口中显示图像

时间:2011-04-02 21:04:55

标签: c# wpf

我想在窗口中显示一个自动扩展到该图像尺寸的图像。 现在,我有一个显示它的代码,但我必须输入窗口的高度和宽度以及图像以正确显示它。有可能这样做吗?

3 个答案:

答案 0 :(得分:0)

当然有可能。 在PictureBox控件中加载图像之前,调整控件的大小以匹配图像大小,然后在PictureBox中加载图像。

甚至更好,让.NET完成工作(但这是winforms):

pictureBox1.SizeMode = PictureBoxSizeMode.AutoSize;

对于WPF,请在您的代码中尝试这个(我没有测试过):

    image1.Width = width;
    image1.Height = height;

其中width和height是您尝试加载的图片的大小。

答案 1 :(得分:0)

可以使WPF窗口适合其内容。在XAML中,将SizeToContent属性设置为“WidthAndHeight”

<Window x:Class ...
        SizeToContent="WidthAndHeight">

现在只需确保您的图像容器大小为源图像,然后设置即可。

答案 2 :(得分:0)

您只需在窗口中设置SizeToContent="WidthAndHeight"属性,请参阅以下概念证明:

<Window x:Class="MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" SizeToContent="WidthAndHeight">
<Grid>
    <Image Stretch="None" Source="Images\img1.jpg"/>
</Grid>

相关问题