You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让图片铺满WPF窗口整个背景?求C#实现代码

WPF图片拉伸失效的解决方法

你的代码里有两个关键问题导致图片拉伸不生效,还有拼写错误:

问题分析

  1. Canvas容器特性:Canvas是绝对布局容器,不会自动调整子元素的尺寸。你只设置了Image的Stretch属性,但没有给Image指定与Canvas匹配的宽高,所以图片只会以原始尺寸显示,不会拉伸。
  2. 代码拼写错误:
    • Stretch =.Fill 多了个前置点,正确写法是 Stretch = Stretch.Fill
    • StretchdDirection 拼写错误,正确是 StretchDirection

修复方案

方案1:给Image绑定Canvas的宽高

修改Image定义,将其宽高绑定到Canvas的实际尺寸,让图片随Canvas大小自动拉伸:

Images ImageOne = new();
public MainWindow()
{
    InitializeComponent();
    MyCanvas.Children.Add(ImageOne.Background);
}

class Images
{
    public Image Background = new() 
    { 
        Source = new BitmapImage(new Uri("chessbackground2.jpg", UriKind.Relative)), 
        Stretch = Stretch.Fill, 
        StretchDirection = StretchDirection.Both,
        // 绑定宽高到Canvas的实际尺寸
        Width = double.NaN,
        Height = double.NaN
    };
}

同时在XAML中给Image添加绑定:

<Canvas x:Name="MyCanvas">
    <Image Stretch="Fill" StretchDirection="Both" 
           Width="{Binding ActualWidth, ElementName=MyCanvas}"
           Height="{Binding ActualHeight, ElementName=MyCanvas}"
           Source="chessbackground2.jpg"/>
</Canvas>

方案2:改用Grid容器

如果不需要绝对布局,直接用Grid代替Canvas,Grid会自动让子元素填充整个容器,无需额外设置宽高:

// 代码里将Image加到Grid中
MyGrid.Children.Add(ImageOne.Background);

对应的XAML:

<Grid x:Name="MyGrid">
    <!-- Image会自动填充整个Grid -->
</Grid>

内容的提问来源于stack exchange,提问作者KieoUK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 04:32:09