[英]Using WPF MVVM Light DispatcherHelper
I have a WPF Application in which some controls properties are bound to properties in the relative viewmodel. 我有一个WPF应用程序,其中一些控件属性绑定到相对viewmodel中的属性。
Here is the relevant XAML code: 这是相关的XAML代码:
[..]
<StackPanel>
<Ellipse Width="20" Height="20" Fill="{Binding ServiceStatus.Colore}"/>
<TextBlock Text="{Binding ServiceStatus.Stato}" FontSize="8"></TextBlock>
</StackPanel>
[..]
This is the DTO: 这是DTO:
public class StatusDTO
{
public Service.StatoServizio ServiceStatus { get; set; }
public string Stato { get; set; }
public SolidColorBrush Colore { get; set; }
}
And this is the ViewModel: 这是ViewModel:
public class MainViewModel : ViewModelBase
{
private StatusDTO _ServiceStatus;
public StatusDTO ServiceStatus
{
get { return _ServiceStatus; }
set { _ServiceStatus = value; }
}
public MainViewModel()
{
[...]
_ServiceStatus = new StatusDTO();
_ServiceStatus.ServiceStatus = SS_UNKNOWN;
_ServiceStatus.Stato = "INITIALIZING...";
_ServiceStatus.Colore = new SolidColorBrush(Colors.Gray);
CheckServiceStatus();
[...]
}
private void CheckServiceStatus()
{
ThreadPool.QueueUserWorkItem(o =>
{
Service.StatoServizio ss = SS_UNKNOWN;
while (true)
{
Thread.Sleep(5000);
ss = Service.ServiceManager.GetServiceStatus();
if (_ServiceStatus.ServiceStatus == ss)
continue;
_ServiceStatus.ServiceStatus = ss;
switch (_ServiceStatus.ServiceStatus)
{
case SS_STOPPED:
_ServiceStatus.Stato = "STOPPED";
_ServiceStatus.Colore = new SolidColorBrush(Colors.Red);
break;
[...]
}
DispatcherHelper.CheckBeginInvokeOnUI(() => { RaisePropertyChanged("ServiceStatus"); }); <----- HERE I GOT THE EXCEPTION
}
});
}
The DispatcherHelper is initialized in App.xaml.cs DispatcherHelper在App.xaml.cs中初始化
When the code executes the lambda in DispatcherHelper.CheckBeginInvokeOnUI I got this exception: 当代码在DispatcherHelper.CheckBeginInvokeOnUI中执行lambda时,我得到了以下异常:
Must create DependencySource on same Thread as the DependencyObject
If I update the _ServiceStatus in the UI thread (as in the constructor of the viewmodel) the ui gets updated. 如果我更新UI线程中的_ServiceStatus(在viewmodel的构造函数中),ui会更新。
My question is: isn't DispatcherHelper.CheckBeginInvokeOnUI there to avoid this issue? 我的问题是:是不是DispatcherHelper.CheckBeginInvokeOnUI有避免这个问题? What am I doing wrong?
我究竟做错了什么? Thank you!
谢谢!
You should either create the Colore
brush on the UI thread or call its Freeze
method on the background thread: 你应该在UI线程上创建
Colore
画笔,或者在后台线程上调用它的Freeze
方法:
case SS_STOPPED:
_ServiceStatus.Stato = "STOPPED";
_ServiceStatus.Colore = new SolidColorBrush(Colors.Red);
_ServiceStatus.Colore.Freeze(); // <--
break;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.