WPF的DataGrid下DataGridCell绑定Brush报错的问题
2020-12-23 02:26
标签:null ora pen horizon mat text main count targe 界面上有个DataGrid,xaml如下 viewmodel如下: 问题是这样的,如果TestModel内部默认的StatusColor不是null,第14行直接add就报错,如果是null,直接add就不报错,不清楚什么原因。那位大佬清楚解释下。 源码下载:下载 WPF的DataGrid下DataGridCell绑定Brush报错的问题 标签:null ora pen horizon mat text main count targe 原文地址:https://www.cnblogs.com/zhengbinlong/p/13575572.html 1 Window x:Class="WTest.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:WTest"
7 mc:Ignorable="d"
8 Title="MainWindow" Height="450" Width="800">
9 Window.Resources>
10 Style TargetType="DataGridCell">
11 Setter Property="Foreground" Value="{Binding StatusColor}" />
12 Style>
13 Window.Resources>
14 Grid>
15 Grid.RowDefinitions>
16 RowDefinition Height="*">RowDefinition>
17 RowDefinition Height="30">RowDefinition>
18 Grid.RowDefinitions>
19 DataGrid ItemsSource="{Binding Collects}">
20 DataGrid.Columns>
21 DataGridTextColumn Binding="{Binding Id}" Header="Id"/>
22 DataGrid.Columns>
23 DataGrid>
24 StackPanel Grid.Row="1" Orientation="Horizontal">
25 Button Content="获取数据" Command="{Binding GetData}" HorizontalAlignment="Left" Height="30" Width="75"/>
26 Button Content="修改第一条" Command="{Binding ChangeFirst}" HorizontalAlignment="Left" Height="30" Width="75"/>
27 StackPanel>
28 Grid>
29 Window>
1 public class MainViewModel : BaseNotifyEntity
2 {
3 private ObservableCollectionTestModel> collects = new ObservableCollectionTestModel>();
4 public ObservableCollectionTestModel> Collects { get => collects; set => NotifyPropertyChanged(nameof(Collects), ref collects, value); }
5
6 public DelegateCommand GetData => new DelegateCommand(async (o) =>
7 {
8 var data = await Datas();
9 int i = 0;
10 data.ForEach((item) =>
11 {
12 //item.StatusColor如果为null那就可以直接add
13 //item.StatusColor不为null的时候这里为什么一定要重设颜色才不报错?,否则直接add就报错了
14 item.StatusColor = i % 2 == 0 ? new SolidColorBrush(Colors.Red) : new SolidColorBrush(Colors.Purple);
15
16 Collects.Add(item);
17 i++;
18 });
19 });
20
21 public async TaskList
文章标题:WPF的DataGrid下DataGridCell绑定Brush报错的问题
文章链接:http://soscw.com/index.php/essay/37698.html