MVVM绑定 填坑,必须在与 DependencyObject 相同的线程上创建 DependencySource
场景:线程里面构建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 }