wpf 如何在wpf中更改datagrid的单个单元格颜色?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16189717/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 08:40:15  来源:igfitidea点击:

How to change single cell color of datagrid in wpf?

c#wpfxamldatagridwpfdatagrid

提问by Vivek Parikh

stage chartI want to change background color of a particular cell of this grid at runtime(show booked seats).i am binding this grid from datatable on window loaded event.i have a record of seats like 'A33'.my code for binding is like this.

阶段图我想在运行时更改此网格的特定单元格的背景颜色(显示预订的座位)。我正在窗口加载事件上从数据表绑定此网格。我有像“A33”这样的座位记录。我的绑定代码就像这个。

MySqlConnection mycon = new MySqlConnection(str);
mycon.Open();
MySqlDataAdapter da = new MySqlDataAdapter("select * from Stage", mycon);
da.Fill(dt);
MyGrid.ItemsSource = dt.DefaultView;

回答by user1064519

change background of specific cell by code :

通过代码更改特定单元格的背景:

   DataGridRow firstRow = dataGrid1.ItemContainerGenerator.ContainerFromItem(dataGrid1.Items[0]) as DataGridRow;
   DataGridCell firstColumnInFirstRow = dataGrid1.Columns[0].GetCellContent(firstRow).Parent as DataGridCell;
   //set background
   firstColumnInFirstRow.Background = Brushes.Red;

回答by H.B.

Your cell-data should have a property IsBooked, then in the DataGrid.CellStyleyou can use a data-trigger on IsBookedto change its backgroud. (There are some other alternativesbesides DataTriggers, but if you just have one boolean conditional i find them to be quite convenient.)

您的单元格数据应该有一个属性IsBooked,然后DataGrid.CellStyle您可以在其中使用数据触发器IsBooked来更改其背景。(除了,还有其他一些选择DataTriggers,但如果你只有一个布尔条件,我发现它们非常方便。)