Search code examples
c#wpfmvvm

Set Canvas Background, Width and Height with MVVM


I have a struggle, I don't know how to set the background and size of a canvas with respect to MVVM, currently, I handle this only in the View part, and work ok, over this image (canvas) I want to draw some rectangle, but I want to be able to do everything according to MVVM pattern.

var bmp = new BitmapImage(new Uri(filename, UriKind.Relative));
ImageBrush brush = new ImageBrush();
brush.ImageSource = bmp;
canvas.Width = bmp.PixelWidth;
canvas.Height = bmp.PixelHeight;
canvas.Background = brush;
canvas.SnapsToDevicePixels = true;

Solution

  • The view model could expose a property with e.g. the image file path

    public string ImagePath { get; set; }
    

    to which you would bind like this

    <Canvas Width="{Binding Background.ImageSource.PixelWidth,
                            RelativeSource={RelativeSource Self}}"
            Height="{Binding Background.ImageSource.PixelHeight,
                             RelativeSource={RelativeSource Self}}"
            SnapsToDevicePixels="True">
        <Canvas.Background>
            <ImageBrush ImageSource="{Binding ImagePath}"/>
        </Canvas.Background>
    </Canvas>
    

    The conversion from string to ImageSource would automatically be performed by an ImageSourceConverter instance in WPF.


    The Bindings would be simpler when the view model exposes a property of type BitmapSource:

    public BitmapSource Image { get; set; }
    

    XAML:

    <Canvas Width="{Binding Image.PixelWidth}"
            Height="{Binding Image.PixelHeight}"
            SnapsToDevicePixels="True">
        <Canvas.Background>
            <ImageBrush ImageSource="{Binding Image}"/>
        </Canvas.Background>
    </Canvas>