我有一个Image
控件绑定到viewmodel中的两个Bitmap
属性(这些不是依赖属性)。根据切换按钮切换源。绑定到切换按钮的触发器工作并切换图像源但是当Bitmap
属性中的任何一个更改时,图像不会更新。显示默认图像(最初设置),但在更改属性时不会更新。视图模型已实现INotifyPropertyChanged,并且当位图更改但未更新Image
控件时会通知代码的其他部分。
仅在设置初始图像时才调用转换器,而不是在后续更新中调用。
<Image Grid.Row="1"
Stretch="Uniform"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
Width="Auto"
Height="Auto">
<Image.Style>
<Style TargetType="{x:Type Image}">
<Style.Triggers>
<DataTrigger Binding="{Binding ToggleImage}" Value="True">
<Setter Property="Source" Value="{Binding ProcessedImage, Converter={StaticResource ImageToSourceConverter},
UpdateSourceTrigger=PropertyChanged, Mode=OneWay}" />
</DataTrigger>
<DataTrigger Binding="{Binding ToggleImage}" Value="False">
<Setter Property="Source" Value="{Binding OriginalImage, Converter={StaticResource ImageToSourceConverter},
UpdateSourceTrigger=PropertyChanged, Mode=OneWay}" />
</DataTrigger>
</Style.Triggers>
</Style>
</Image.Style>
</Image>
这里是转换器代码
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Windows;
using System.Windows.Data;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace OMR_Scanner_Application.Converters
{
class ImageToSourceConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
Bitmap image = value as Bitmap;
if (image != null)
{
MemoryStream ms = new MemoryStream();
image.Save(ms, ImageFormat.Bmp);
ms.Seek(0, SeekOrigin.Begin);
BitmapImage bi = new BitmapImage();
bi.CacheOption = BitmapCacheOption.None;
bi.BeginInit();
bi.StreamSource = ms;
bi.EndInit();
return bi;
}
return null;
}
public object ConvertBack(object value, Type targetType,
object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
}