在static
C# 方法中,我这样做var brush = new LinearGradientBrush(_snazzyGradient);
了,并且这一行引发了异常。 _snazzyGradient
定义如下:
private static readonly GradientStopCollection _snazzyGradient =
new GradientStopCollection
{
new GradientStop((Color)ColorConverter.ConvertFromString("#DBF3FF"), 0.0),
new GradientStop((Color)ColorConverter.ConvertFromString("#A3CCE0"), 1.0)
};
包含方法和_snazzyGradient
实现的类INotifyPropertyChanged
(如果重要),并用作视图模型。使用的静态方法_snazzyGradient
在类的构造函数中被调用。在一个UserControl
类中,我使用引用的构造函数将依赖属性的值设置为该视图模型类的新实例_snazzyGradient
。
当我调试我的应用程序时var brush = new LinearGradientBrush(_snazzyGradient);
,我得到以下异常:
System.InvalidOperationException 被捕获 Message=调用线程无法访问此对象,因为不同的线程拥有它。Source = WindowsBase StackTrace:在 System.Windows.Threading.Dispatcher.VerifyAccess() 在 System.Windows.Threading.DispatcherObject.VerifyAccess() 在 System.Windows.Freezable.ReadPreamble() 在 System.Windows.Media.GradientStopCollection.OnInheritanceContextChangedCore( EventArgs args) 在 System.Windows.DependencyObject.OnInheritanceContextChanged(EventArgs args) 在 System.Windows.Freezable.AddInheritanceContext(DependencyObject 上下文,DependencyProperty 属性) 在 System.Windows.DependencyObject.ProvideSelfAsInheritanceContext(DependencyObject doValue, DependencyProperty dp) 在 System.Windows。依赖对象。
我已经将我的依赖属性更改UserControl
为以下内容:
public ParentViewModel Data
{
get
{
return (ParentViewModel)Dispatcher.Invoke(
DispatcherPriority.Background,
(DispatcherOperationCallback)delegate
{
return GetValue(DataProperty);
},
DataProperty
);
}
set
{
Dispatcher.BeginInvoke(
DispatcherPriority.Background,
(SendOrPostCallback)delegate
{
SetValue(DataProperty, value);
},
value
);
}
}
我的问题是,我怎样才能摆脱这个InvalidOperationException
?Dispatcher
必须在我的视图模型中放置一堆与线程相关的调用似乎是不对的。我不应该将其定义_snazzyGradient
为静态字段,而是从静态方法返回吗?我不知道这是否会有所帮助。我绝对想要多线程,因为我不希望 GUI 在读/写必要的文件时陷入困境,诸如此类。也许我的问题源于在视图模型中使用GradientStop
(继承自DependencyObject
)等;也许这些应该从 my 提供给视图模型的构造函数UserControl
?