【问题标题】:Changing font to DataGridView row is not working in WinForms C#将字体更改为 DataGridView 行在 WinForms C# 中不起作用
【发布时间】:2019-05-06 05:40:52
【问题描述】:

我有管理 datagridview 对象的方法:

internal static void LoadChannelsInGrid(DataGridView dg, Label noDataLbl, string feedUrl)
{
    var response = RssManager.GetRss(feedUrl);
    if (response != null)
    {
        noDataLbl.Visible = false;
        dg.Visible = true;
        var items = response.OrderByDescending(s => s.PubDateUnix);
        dg.DataSource = items.ToArray();

        FontifyDataGrid(dg);
    }
    else
    {
        noDataLbl.Visible = true;
        dg.Visible = false;
    }
}

private static void FontifyDataGrid(DataGridView dg)
{
    for (var i = 0; i < dg.Rows.Count; i++)
    {
        var item = dg.Rows[i].DataBoundItem as ChannelData;
        if (item == null)
        {
            continue;
        }

        if (!item.IsLoaded)
        {
            var actualFont = new Font("Microsoft Sans Serif", 7.8f, FontStyle.Bold);
            dg.Rows[i].DefaultCellStyle.Font = actualFont;
        }
    }
}

我打电话给:

LoadChannelsInGrid(dataGridView1, noDataLbl, "https://....");

似乎行(哪个模型项满足IsLoaded 值)没有粗体样式,看起来仍然很规则。

为什么?

【问题讨论】:

  • 在 RowPostPaint 事件中,尝试类似:if (!((dg.Rows[e.RowIndex].DataBoundItem as ChannelData)?.IsLoaded)) { dg.Rows[e.ColumnIndex].DefaultCellStyle.Font = [newFont]; }。您应该将该字体存储在某处,因此您无需每次都使用new。当条件发生变化时,我似乎不想用其他东西代替它。
  • 您在构造函数中对DataGridView 的单元格和行所做的更改(在表单加载事件之前)将不会被保留并且它们将丢失。这不仅仅是关于样式,而是关于行和单元格的所有更改。 this是这样吗?此外,正如 Jimi 已经提到的,一般而言,您可能需要考虑使用单元格/行事件,例如 CellFormattingRowPrepaint、...

标签: c# winforms datagridview


【解决方案1】:

如果我理解正确,当 IsLoaded 属性为 true 时,您需要将字体设为粗体。

在这种情况下,您需要将您的 if (!item.IsLoaded) 更新为 if (item.IsLoaded)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-18
    • 1970-01-01
    • 2012-07-31
    • 1970-01-01
    • 1970-01-01
    • 2011-10-31
    相关资源
    最近更新 更多