【发布时间】:2018-03-30 14:10:51
【问题描述】:
我有一个 WPF 图像控件,它的源属性绑定到返回 Image 对象的属性“ImageSrc”。
<Window x:Class="My.Apps.WPF.Main"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:viewmodel="clr-namespace:My.Apps.WPF.ViewModels"
xmlns:classes="clr-namespace:My.Apps.WPF.Classes"
>
<Window.Resources>
<viewmodel:MyViewModel x:Key="myViewModel" />
<classes:ImgToSrcConverter x:Key="imgToSrcConverter" />
</Window.Resources>
<Grid x:Name="TopGrid" DataContext="{StaticResource myViewModel}">
<Image Grid.Row="0">
<Image.Source>
<MultiBinding NotifyOnTargetUpdated="True" Converter="{StaticResource imgToSrcConverter}">
<Binding Path="ImageSrc" />
<Binding Path="." />
</MultiBinding>
</Image.Source>
</Image>
</Grid>
</Window>
转换器:
public class ImgToSrcConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
Image image = values[0] as Image;
if (image != null)
{
MemoryStream ms = new MemoryStream();
image.Save(ms, image.RawFormat);
ms.Seek(0, SeekOrigin.Begin);
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.StreamSource = ms;
bi.EndInit();
ViewModel vm = values[1] as ViewModel;
bi.DownloadCompleted += (s, e) =>
{
vm.Method();
};
return bi;
}
return null;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
我遇到的问题是 BitmapImage 的 DownloadCompleted 事件从未引发过这样一行:
vm.Method();
永远不会执行,因此我的视图模型中的 Method() 永远不会执行。
当我使用视图模型中绑定的 ImageSrc 属性从视图中的 Image 对象更新 Source 属性时,我检查了转换器是否正确执行。
我做错了什么?
【问题讨论】:
标签: c# wpf mvvm visual-studio-2008 .net-3.5