【问题标题】:How to change single cell color of datagrid in wpf?如何在 wpf 中更改数据网格的单个单元格颜色?
【发布时间】:2013-04-17 20:52:45
【问题描述】:

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

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

【问题讨论】:

    标签: c# wpf xaml datagrid wpfdatagrid


    【解决方案1】:

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

       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;
    

    【讨论】:

    • 一般情况下应该避免使用ItemContainerGenerator,它很难看并且在虚拟化控件上会失败。
    【解决方案2】:

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-06
    • 2012-09-30
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多