我试图异步加载图像。异步加载C#中的BitmapImage
主窗口代码
public partial class MainWindow : Window
{
private Data data = new Data();
public MainWindow()
{
InitializeComponent();
this.DataContext = data;
}
private async void button_Click(object sender, RoutedEventArgs e)
{
data.Image = await Data.GetNewImageAsync();
}
}
数据类
public class Data : INotifyPropertyChanged
{
private BitmapImage _Image = new BitmapImage();
public BitmapImage Image { get { return _Image; } set { _Image = value; OnPropertyChanged("Image"); } }
public static BitmapImage GetNewImage()
{
return new BitmapImage(new Uri("http://www.diseno-art.com/news_content/wp-content/uploads/2012/09/2013-Jaguar-F-Type-1.jpg"));
}
public async static Task<BitmapImage> GetNewImageAsync()
{
return await Task.Run(() => GetNewImage());
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
WPF代码
<Button Name="button" Click="button_Click">Image</Button>
<Image Grid.Row="1" Source="{Binding Path=Image, UpdateSourceTrigger=PropertyChanged}"></Image>
问题
我得到异常:
System.ArgumentException: “必须在相同的线程 作为DependencyObject的创建DependencySource”
...在此行中: PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
但是,如果我改变的BitmapImage字符串此代码工作正常。
我在做什么错?
作为说明,在图像绑定上设置'UpdateSourceTrigger = PropertyChanged'是没有意义的。它只对TwoWay和OneWayToSource绑定产生影响。 – Clemens