0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

WPFのImageのSourceがNullの場合の対策

Last updated at Posted at 2021-07-04

はじめに

WPFを使っていて、xamlで以下のようなコーディングをした際のことです

    <Image Source="{Binding ImageFilePath}"
           Width="100"
           Height="100"/>

.NetFramework4.8のときは、このImageFilePathがnullや空文字でもすぐに表示されたのですが、.NET5に変更した際に、エラーが起きて、表示がとても遅くなってしまいました。

エラーの内はこんな感じですね

例外がスローされました: 'System.NotSupportedException' (System.ComponentModel.TypeConverter.dll の中)
例外がスローされました: 'System.NotSupportedException' (PresentationCore.dll の中)
System.Windows.Data Error: 23 : Cannot convert '' from type '' to type 'System.Windows.Media.ImageSource'

対策

対策といえばググりましょうということで、いろいろと調べましたが、UWPのImageのSourceにnullや空文字をx:Bindしたときの対処方法(対処できない)という記事で、TargetNullValueを設定すればよさそうということがわかりました。
さらに調べて、TargetNullValue={x:Null} とすることで対策できました。

    <Image Source="{Binding ImageFilePath, TargetNullValue={x:Null}}"
           Width="100"
           Height="100"/>

以上、できてしまえば簡単ですが、忘れてしまいそうだったので、備忘録もかねて記事とさせていただきました。

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?