简体   繁体   English

具有可变列数的WPF Datagrid并根据值更改背景色

[英]WPF Datagrid with variable number of columns AND change background color depending on value

I'm trying to make a grid that represent bookings over a month(excel style). 我试图做一个网格,代表一个月的预订(Excel风格)。

For this I have used the WPF Datagrid and defined my column in C# code: 为此,我使用了WPF Datagrid并在C#代码中定义了我的列:

for (int i = 0; i < noOfDaysInMonth; i++)
{
        DataGridTextColumn tmpColumn = new DataGridTextColumn
        {
               Header = (i + 1).ToString(),
               Binding = new Binding("CellStrings[" + i + "]"),
        };

overviewBookingsDataGrid.Columns.Add(tmpColumn); 

Now this works fine. 现在可以正常工作了。 The problem I got is that I don´t know how to style the background color of each cell depending on if the slot is fully booked, partially booked or empty. 我遇到的问题是,我不知道如何为每个单元格设置背景颜色,具体取决于插槽是否已满,部分预定或空了。 All examples I have found has been in XAML and defines it togheter with the column and I don't know that translates to C#. 我发现的所有示例都在XAML中,并使用该列将其定义为togheter,但我不知道这会转换为C#。

You need to define a datagridcell style in your XAML. 您需要在XAML中定义datagridcell样式。 Set some triggers based on the cell's Tag property. 根据单元格的Tag属性设置一些触发器。 For instance if it is "Green" then color your cell green. 例如,如果它是“绿色”,则将您的单元格涂成绿色。

Once you have populated your datagrid you can iterate through your table in code, get the datagridcell for each required item, set the cell's tag to a proper value and the style triggers will take care of coloring the cell for you (if you want to clear the background color, set the Tag back to null). 填充数据网格后,您可以遍历代码中的表,获取每个必需项的datagridcell,将单元格的标签设置为适当的值,样式触发器将为您着色单元格(如果您想清除背景颜色,则将Tag设置回null)。 Or, if you want to avoid XAML, you can directly set the cells background. 或者,如果要避免XAML,可以直接设置单元格背景。

There are plenty of examples on the web how to retrieve a datagridcell for a given item, but I'll give one word of warning - because the wpf datagrid is virtualized by default, you'll need to scroll your items into view and call UpdateLayout() on the item's datagridrow, before you can safely access a datagridcell for a given datagridrow. 网上有很多示例,如何检索给定项目的datagridcell,但我会提一个警告-由于wpf datagrid是默认虚拟化的,因此您需要将项目滚动到视图中并调用UpdateLayout ()在项目的datagridrow上,然后可以安全地访问给定datagridrow的datagridcell。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM