在MVVM/WPF中从BackgroundWorker更新位图
本文关键字:BackgroundWorker 更新 位图 中从 WPF MVVM | 更新日期: 2023-09-27 18:01:27
我正在尝试从BackgroundWorker线程更新UI中的BitmapImage。我知道足够的背景工作者一般设置他们,以及如何使用ObservableCollection更新列表从BackgroundWorker,但我正在努力获得图像更新。
设置
现在看起来是这样的:
XAML:<Image Source="{Binding ImageSource}" />
ViewModel:
public class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
private BitmapImage ImageSource_;
public BitmapImage ImageSource
{
get { return ImageSource_; }
set { ImageSource_= value; NotifyPropertyChanged("ImageSource"); }
}
private BackgroundWorker UpdateImageBGW = new BackgroundWorker();
public ViewModel()
{
// this works fine
ImageSource = UpdateImage();
UpdateImageBGW.DoWork += new DoWorkEventHandler(UpdateImage_DoWork);
UpdateImageBGW.RunWorkerAsync();
}
private void UpdateImage_DoWork(object sender, DoWorkEventArgs e)
{
// this gets called fine and grabs the updated image, but setting it to
// ImageSource never updates the UI
ImageSource = UpdateImage();
}
}
问题是您正在尝试从后台线程更新UI元素。由于安全原因,您不能与任何其他线程在UI线程上创建的元素进行交互。如果你想从一个后台线程更新UI,这样做:
Dispatcher.Invoke((Action)delegate() { /*update UI thread here*/ });
此方法将创建允许您与UI线程通信的桥接。查看这个stackoverflow线程,它有更多示例。
祝你好运
像这样使用ObservableCollection
public partial class MainWindow : Window
{
private ObservableCollection<int> myVar;
public ObservableCollection<int> MyProperty
{
get { return myVar; }
set { myVar = value; }
}
BackgroundWorker bw;
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
MyProperty = new ObservableCollection<int>();
bw = new BackgroundWorker();
bw.DoWork += bw_DoWork;
bw.RunWorkerAsync();
}
void bw_DoWork(object sender, DoWorkEventArgs e)
{
for(int i = 0; i < 10;i++)
{
MyProperty.Add(i);
}
}
}
xaml: 和
<ListBox HorizontalAlignment="Left" ItemsSource="{Binding MyProperty}" Height="224" Margin="93,50,0,0" VerticalAlignment="Top" Width="321"/>