Search code examples
c#wpfxaml

How can I make an image fit the entire background of a WPF window? Like fill the window. c# code


So I tried stretching the image but it didnt work. Not sure if thats what Im meant to do and I cant find anything online that would help. MyCanvas.Children.Add(ImageOne.Background);

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 =.Fill, StretchDirection = StretchdDirection.Both };
}

Solution

  • You may use an ImageBrush as the Window's Background:

    <Window x:Class="YourProject.MainWindow" ...>
        <Window.Background>
            <ImageBrush ImageSource="chessbackground2.jpg"/>
        </Window.Background>
        <Grid>
            ...
        </Grid>
    </Window>
    

    In code behind of the Window class, it would be

    Background = new ImageBrush(
        new BitmapImage(
            new Uri("chessbackground2.jpg", UriKind.Relative)));