我正在启动一个新线程并尝试通过我的视图模型中定义的属性更新 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 void ExecuteCommand(object obj) { InvokeCallThroughAnonymousDelegateThread(); }
private void InvokeCallThroughAnonymousDelegateThread()
{
ThreadStart start = delegate()
{
UserInput = "Calling from diff thread";
};
new Thread(start).Start();
}