场景:线程里面构建MVVM实体类,实体类包含 Brush 属性时,构建 SolidColorBrush 需要UI线程,否则会报 “必须在与 DependencyObject 相同的线程上创建 DependencySource”
MVVM实体类
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media;
namespace WpfApp3
{
public class TestInfo : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public Brush BG { get; set; }
}
}
下面是报错代码:
<Window x:Class="WpfApp3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp3"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid Background="{Binding BG}">
</Grid>
</Window>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApp3
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Loaded += MainWindow_Loaded;
}
private async void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
TestInfo info = new TestInfo();
await Task.Run(() =>
{
info.BG = new SolidColorBrush(Colors.Red);
});
this.DataContext = info;
}
}
}
原因:
因为 info.BG = new SolidColorBrush(Colors.Red); 这行报错,原因是 构建 SolidColorBrush 需要UI 线程!!
调整后的后端代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApp3
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Loaded += MainWindow_Loaded;
}
private async void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
TestInfo info = new TestInfo();
await Task.Run(() =>
{
Brush brush = null;
Dispatcher.Invoke(() =>
{
brush = new SolidColorBrush(Colors.Red);
});
info.BG = brush;
});
this.DataContext = info;
}
}
}