Sam Alex
Sam Alex

Reputation: 442

How do I set background image to a Canvas

Wpf Canvas Background image does not display selected image from local path

XAML Code

  <Canvas x:Name="LayoutRoot" Margin="485,24,0,0" HorizontalAlignment="Left" Width="341" Height="506" VerticalAlignment="Top">
                <Canvas.Background>
                    <ImageBrush ImageSource="{Binding BGImage}"/>
                </Canvas.Background>
            </Canvas>

MVVM code

private String _BGImage = @"‪C:/Users/sam/Desktop/photo-5.jpg";

public String BGImage
    {
        get
        {
            return this._BGImage;
        }
        set
        {
            this._BGImage = value;
            NotifyPropertyChanged("BGImage");
        }
    }

Why this image not display on canvas background

Upvotes: 6

Views: 20358

Answers (3)

Sean Cogan
Sean Cogan

Reputation: 2586

Your viewmodel code for BGImage should look something like this:

private ImageSource _BGImage = new BitmapImage(new Uri(@"C:\Users\sam\Desktop\photo-5.jpg", UriKind.Absolute))

public ImageSource BGImage
{
    get { return _BGImage; }
    set
    {
        _BGImage= value;
        NotifyPropertyChanged("BGImage");
    }
}

Upvotes: 6

memory of a dream
memory of a dream

Reputation: 1267

or you can try using a converter

<UserControl.Resources>
<local:StringToImageConverter x:Key="StringToImageConverter" />
</UserControl.Resources>

...

<Canvas x:Name="LayoutRoot" Margin="485,24,0,0" HorizontalAlignment="Left" Width="341" Height="506" VerticalAlignment="Top">
                <Canvas.Background>
                    <ImageBrush ImageSource="{Binding Path=BGImage, Converter={StaticResource StringToImageConverter}}"/>
                </Canvas.Background>
            </Canvas>

and this is the converter

public class StringToImageConverter : IValueConverter
    {
      public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
      {
        if (value.GetType() != typeof(string))
        {
          throw new InvalidOperationException("The value must be a string");
        }

        return new BitmapImage(new Uri((string)value));
      }

      public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
      {
        return null;
      }
    }

of course you would still need to check if the string is a valid URI

Upvotes: 7

Muds
Muds

Reputation: 4116

Well you need to have BGImage as BitmapImage rather than string

public BitmapImage BGImage
{
    get
    {
        return new BitmapImage((new Uri(this._BGImage, UriKind.Absolute)));
    }
}

If you are changing image dynamically then you have to raise property changed to notify UI

Upvotes: 0

Related Questions