1. 程式人生 > >WPF的Image控制元件的資源切換

WPF的Image控制元件的資源切換

首先需要做一個資源類,把圖片資源放到這個類裡。

然後需要一個轉換Converter類。

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
		{

			System.Drawing.Bitmap bitmap = (System.Drawing.Bitmap)value;
			
			if (bitmap != null)
			{
				System.Windows.Media.ImageSource source = Imaging.CreateBitmapSourceFromHBitmap(bitmap.GetHbitmap(),
					IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
				return source;
			}
			else
				return null;
		}

		public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
		{
			throw new NotImplementedException();
		}

最後就是在xaml裡用了。

<Image Width="300" Height="80" Source="{Binding NameBitmap,Converter={StaticResource ImageConverter}}"  RenderOptions.BitmapScalingMode="Fant"></Image>