場景:線程裏面構建MVVM實體類,實體類包含 Brush 屬性時,構建 SolidColorBrush 需要UI線程,否則會報 “必須在與 DependencyObject 相同的線程上創建 DependencySource”
MVVM實體類
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Linq; 5 using System.Text; 6 using System.Threading.Tasks; 7 using System.Windows.Media; 8 9 namespace WpfApp3 10 { 11 public class TestInfo : INotifyPropertyChanged 12 { 13 public event PropertyChangedEventHandler PropertyChanged; 14 15 public Brush BG { get; set; } 16 } 17 }
下面是報錯代碼:
1 <Window x:Class="WpfApp3.MainWindow" 2 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 3 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 4 xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 5 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 6 xmlns:local="clr-namespace:WpfApp3" 7 mc:Ignorable="d" 8 Title="MainWindow" Height="450" Width="800"> 9 <Grid Background="{Binding BG}"> 10 11 </Grid> 12 </Window>
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using System.Windows; 7 using System.Windows.Controls; 8 using System.Windows.Data; 9 using System.Windows.Documents; 10 using System.Windows.Input; 11 using System.Windows.Media; 12 using System.Windows.Media.Imaging; 13 using System.Windows.Navigation; 14 using System.Windows.Shapes; 15 16 namespace WpfApp3 17 { 18 /// <summary> 19 /// MainWindow.xaml 的交互邏輯 20 /// </summary> 21 public partial class MainWindow : Window 22 { 23 public MainWindow() 24 { 25 InitializeComponent(); 26 27 Loaded += MainWindow_Loaded; 28 } 29 30 private async void MainWindow_Loaded(object sender, RoutedEventArgs e) 31 { 32 TestInfo info = new TestInfo(); 33 await Task.Run(() => 34 { 35 info.BG = new SolidColorBrush(Colors.Red); 36 }); 37 this.DataContext = info; 38 } 39 } 40 }
原因:
因爲 info.BG = new SolidColorBrush(Colors.Red); 這行報錯,原因是 構建 SolidColorBrush 需要UI 線程!!
調整後的後端代碼:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using System.Windows; 7 using System.Windows.Controls; 8 using System.Windows.Data; 9 using System.Windows.Documents; 10 using System.Windows.Input; 11 using System.Windows.Media; 12 using System.Windows.Media.Imaging; 13 using System.Windows.Navigation; 14 using System.Windows.Shapes; 15 16 namespace WpfApp3 17 { 18 /// <summary> 19 /// MainWindow.xaml 的交互邏輯 20 /// </summary> 21 public partial class MainWindow : Window 22 { 23 public MainWindow() 24 { 25 InitializeComponent(); 26 27 Loaded += MainWindow_Loaded; 28 } 29 30 private async void MainWindow_Loaded(object sender, RoutedEventArgs e) 31 { 32 TestInfo info = new TestInfo(); 33 await Task.Run(() => 34 { 35 Brush brush = null; 36 Dispatcher.Invoke(() => 37 { 38 brush = new SolidColorBrush(Colors.Red); 39 }); 40 info.BG = brush; 41 }); 42 this.DataContext = info; 43 } 44 } 45 }