【问题标题】:Datagrid formatting rows数据网格格式化行
【发布时间】:2014-05-02 13:03:57
【问题描述】:

我有一个数据网格,我正在尝试使用 datagrid_LoadingRow 事件处理程序更改各个行的颜色。我遇到的问题是,它将数据网格中的每一行着色为相同的颜色,而不是根据满足的条件为每一行着色。

这是我的代码,如何将其应用于每个单独的行?

    private void schDataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
    {
        foreach (DataRowView dr in schDataGrid.Items)
        {
            string DUEDATE = dr["DUEDATE"].ToString();

            DateTime now = Convert.ToDateTime(DateTime.Now.ToString("dd/MM/yyyy"));
            DateTime compareDate = Convert.ToDateTime(DUEDATE);
            TimeSpan difference = now - compareDate;

            if (difference.Days <= 0)
            {
                e.Row.Background = new SolidColorBrush(Colors.ForestGreen);
                e.Row.Foreground = new SolidColorBrush(Colors.White);
            }
            else if (difference.Days > 0 && difference.Days <= 60)
            {
                e.Row.Background = new SolidColorBrush(Colors.Orange);
                e.Row.Foreground = new SolidColorBrush(Colors.Black);
            }
            else if (difference.Days > 60)
            {
                e.Row.Background = new SolidColorBrush(Colors.Red);
                e.Row.Foreground = new SolidColorBrush(Colors.White);
            }
        }
    }

一如既往地感谢您的帮助。

【问题讨论】:

  • Paint 事件会更有用。这是一个建议。

标签: c# wpf datagrid


【解决方案1】:

为每一行调用函数 schDataGrid_LoadingRow。 因此,不要循环所有项目,而是取出该行的项目:

        var dr = e.Row.Item as yourItem
        // Other stuff....
        if (difference.Days <= 0)
        {
            e.Row.Background = new SolidColorBrush(Colors.ForestGreen);
            e.Row.Foreground = new SolidColorBrush(Colors.White);
        }
        else if (difference.Days > 0 && difference.Days <= 60)
        {
            e.Row.Background = new SolidColorBrush(Colors.Orange);
            e.Row.Foreground = new SolidColorBrush(Colors.Black);
        }
        else if (difference.Days > 60)
        {
            e.Row.Background = new SolidColorBrush(Colors.Red);
            e.Row.Foreground = new SolidColorBrush(Colors.White);
        }

【讨论】:

    猜你喜欢
    • 2014-06-11
    • 1970-01-01
    • 2011-12-20
    • 1970-01-01
    • 2017-07-03
    • 1970-01-01
    • 1970-01-01
    • 2012-09-14
    • 2014-04-27
    相关资源
    最近更新 更多