staticC#のメソッドで を実行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)
};
method と_snazzyGradientimplementsの両方を含むクラスINotifyPropertyChanged(重要な場合) であり、ビュー モデルとして使用されます。を使用する静的メソッドは_snazzyGradient、クラスのコンストラクターで呼び出されます。を参照するコンストラクターを使用して、UserControlクラス内で依存関係プロパティの値をそのビュー モデル クラスの新しいインスタンスに設定します_snazzyGradient。
アプリをデバッグしているときに、var brush = new LinearGradientBrush(_snazzyGradient);行で次の例外が発生します。
System.InvalidOperationException がキャッチされました Message=別のスレッドがこのオブジェクトを所有しているため、呼び出しスレッドはこのオブジェクトにアクセスできません。ソース = WindowsBase StackTrace: System.Windows.Threading.Dispatcher.VerifyAccess() で System.Windows.Threading.DispatcherObject.VerifyAccess() で System.Windows.Freezable.ReadPreamble() で System.Windows.Media.GradientStopCollection.OnInheritanceContextChangedCore( System.Windows.DependencyObject.OnInheritanceContextChanged(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(inherits from ) などを使用することに起因します。DependencyObjectおそらく、それらは my からビューモデルのコンストラクターに与えられるべきUserControlですか?