Dot-Net

圖像 UriSource 和數據綁定

  • August 21, 2008

我正在嘗試將自定義對象列表綁定到 WPF 圖像,如下所示:

<Image>
   <Image.Source>
       <BitmapImage UriSource="{Binding Path=ImagePath}" />
   </Image.Source>
</Image>

但它不起作用。這是我得到的錯誤:

“必須設置屬性 ‘UriSource’ 或屬性 ‘StreamSource’。”

我錯過了什麼?

WPF 具有用於某些類型的內置轉換器。如果將 Image 的Source屬性綁定到 astringUri值,WPF 將使用ImageSourceConverter將值轉換為ImageSource.

所以

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

如果 ImageSource 屬性是圖像的有效 URI 的字元串表示形式,它將起作用。

您當然可以滾動自己的綁定轉換器:

public class ImageConverter : IValueConverter
{
   public object Convert(
       object value, Type targetType, object parameter, CultureInfo culture)
   {
       return new BitmapImage(new Uri(value.ToString()));
   }

   public object ConvertBack(
       object value, Type targetType, object parameter, CultureInfo culture)
   {
       throw new NotSupportedException();
   }
}

並像這樣使用它:

<Image Source="{Binding ImageSource, Converter={StaticResource ImageConverter}}"/>

引用自:https://stackoverflow.com/questions/20586