0

I have a WPF MVVM application - and I currently have an image bound to a source string.

ViewModel Code

public string PieceImage
{
    get => this.pieceImage;
    set => this.SetProperty(ref this.pieceImage, value);
}

XAML Code

<Image Source="{Binding PieceImage}" />

So this works correctly if for example I assign this to the 'PieceImage' property:

this.PieceImage = "../Images/King.png"

I'm wondering what the best practise is for displaying no image?

It works if I set it to null or an invalid string:

this.PieceImage = null;
this.PieceImage = "../Images/ImageThatDoesntExist.png";

However for both I get a warning in the output along the lines of:

System.Windows.Data Error: 23 : Cannot convert '<null>' from type '<null>' to type 'System.Windows.Media.ImageSource' for 'en-US' culture with default conversions; consider using Converter property of Binding. NotSupportedException:'System.NotSupportedException: ImageSourceConverter cannot convert from (null).

This isn't a game-breaker as the application works as expected - but it seems like bad practise to be writing code that throws errors/warnings in the output log!

Any input into what I should assign the source to would be much appreciated.

AidanH
  • 502
  • 5
  • 24
  • What's your images look like? Paths are way more efficient and vector based so they're usually crisper. – Andy Jun 12 '21 at 15:18

1 Answers1

1

If you didn't want to show image you can hide the Image without changing source

<Image Visibility="Collapsed" Source="{Binding PieceImage}" />

You can set Visibility as Hidden if you want to hide image but Space for Image is preserved

sai vineeth
  • 891
  • 2
  • 5
  • 11
  • Thanks! This is a pretty good solution. I'll see if any more solutions come along, and if not I'll mark this as the answer. – AidanH Jun 12 '21 at 14:22