Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Datagrid单元格背景颜色绑定_C#_Wpf_Binding_Datagrid_Background - Fatal编程技术网

C# Datagrid单元格背景颜色绑定

C# Datagrid单元格背景颜色绑定,c#,wpf,binding,datagrid,background,C#,Wpf,Binding,Datagrid,Background,我有一个DataGrid,需要在一些单元格上设置单独的背景颜色,并在选择时更改单元格的颜色。 更改选定内容的颜色效果很好,如果尝试在不绑定的情况下设置背景色,效果也会很好。我想我的装订是错的 因此,我在xaml中使用了这段代码 <Style TargetType="{x:Type DataGridCell}" x:Key="NumberCell"> <Style.Setters> <Setter Property="Back

我有一个DataGrid,需要在一些单元格上设置单独的背景颜色,并在选择时更改单元格的颜色。 更改选定内容的颜色效果很好,如果尝试在不绑定的情况下设置背景色,效果也会很好。我想我的装订是错的

因此,我在xaml中使用了这段代码

<Style TargetType="{x:Type DataGridCell}" x:Key="NumberCell">

        <Style.Setters>
            <Setter Property="Background" Value="{Binding RelativeSource={RelativeSource FindAncestor},Path=StatusColor}"></Setter>
        </Style.Setters>
        <Style.Triggers>
            <Trigger Property="DataGridCell.IsSelected" Value="True" >
                <Setter Property="Background" Value="{StaticResource LoudBrush}" />
                <Setter Property="BorderBrush" Value="{StaticResource LoudBrush}" />
                <Setter Property="VerticalContentAlignment" Value="Center" />
            </Trigger>
        </Style.Triggers>
    </Style>

第一件事第一。。。请帮自己一个忙,不要在代码背后操纵UI对象。绑定到集合控件的正确方法是实现
INotifyPropertyChanged
接口,定义公共
ObservableCollection
属性,并将其数据绑定到
DataGrid。ItemsSource
属性:

<DataGrid ItemsSource="{Binding Items}" />
您可以根据自己的需要随意使用这些颜色,也可以让它们保持透明,这样它们就不会隐藏您的
触发器
颜色


如果我误解了您的问题,请告诉我。

触发器工作正常,但下次我将使用您的方法解决问题。我想我的问题在这一行:。我包含每行的颜色,但每次显示默认颜色时。是的,
绑定
无效。。。您试图绑定到什么?在CalenderWorkEntry中有一个字符串StatusColor,我想将StatusColor绑定到style.setter。抱歉,我认为我无法帮助您完成此操作。。。你这样做真是一团糟。如果您以正常的WPF方式执行此操作,那么修复将非常简单。。。事实上。。。没那么简单。通常,您会将一组项绑定到
ItemsSource
属性-这将为您提供每行一项,并且所有列都可以访问该行数据。你的代码把事情搞砸了。此外,更常见的做法是创建一个包含UI中所需的所有属性的数据类型,但您使用的是
IDictionary
,这只会让一切变得更加棘手。很抱歉
public class CalenderWorkplanEntry
{

    public string Fullname { get; set; }
    public int UserId { get; set; }
    public string StatusColor { get; set; }
    public WorkPlanAppointment Appointment { get; set; }

}
<DataGrid ItemsSource="{Binding Items}" />
<DataGrid.Resources>
    <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent" />
    <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="Transparent" />
    <SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}" Color="Black" />
    <SolidColorBrush x:Key="{x:Static SystemColors.ControlTextBrushKey}" Color="Black" />
</DataGrid.Resources>