我正在启动一个新线程并尝试通过我的 View 模型中定义的属性更新 UI 元素并且我能够在没有任何错误的情况下执行此操作,但是如果我尝试通过代码隐藏更新 UI 元素,它会抛出已知的UI 访问错误(“调用线程无法访问此对象,因为另一个线程拥有它。”)。第一个问题是..这两种方法有什么区别?第二个问题是什么时候我会在 ViewModel 中理想地使用 Disptacher?
代码隐藏
private void Button_Click(object sender, RoutedEventArgs e)
{
Thread th = new Thread(new ThreadStart(delegate()
{
textbox.Text = "Rajib";
}
));
th.Start();
}
//inside XAML
<TextBox x:Name="textbox" Text="{Binding UserInput, Mode=TwoWay}" />
MVVM
public string UserInput
{
get { return _UserInput; }
set { _UserInput = value; OnPropertyChanged("UserInput"); }
}
//在单击按钮时通过 ICommand 属性调用 公共(public)无效执行命令(对象对象) { InvokeCallThroughAnonymousDelegateThread();
private void InvokeCallThroughAnonymousDelegateThread()
{
ThreadStart start = delegate()
{
UserInput = "Calling from diff thread";
};
new Thread(start).Start();
}
最佳答案
任何更新 UI 的尝试都必须在调度程序线程中完成。但是,对于属性更改事件,当事件从后台线程引发时,WPF 自动为您调度。您可以在 Bea Costa(前 WPF 数据绑定(bind) PM)的博客上阅读更多相关信息:
http://bea.stollnitz.com/blog/?p=34
他们打算对 INotifyCollectionChanged
事件做同样的事情,但在以前的版本中从来没有考虑过。对于 4.5 they will now be synchronizing collection changed events automatically除了 INotifyPropertyChanged
。
关于wpf - 使用 WPF 的 MVVM 模式是否不需要 Dispatcher?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10031578/