首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将DataGridViewCellStyle还原为其继承的值

如何将DataGridViewCellStyle还原为其继承的值
EN

Stack Overflow用户
提问于 2016-04-11 10:12:07
回答 1查看 852关注 0票数 3

我有一个DataGridView,我想通过给这些值一个不同的ForeColor来显示那些值被更改的操作符。操作员可以通过单击“丢弃”按钮来决定放弃所有更改。在这种情况下,我需要让单元格使用继承的样式。

我的问题是,一旦我创建了一个CellStyle来指示它被更改了,我就不能撤销它,以便该单元格使用继承的样式。

我做了些调查。在Windows窗体DataGridView控件中的单元格样式 MSDN一文中警告:

缓存存储在单元格样式属性中的值非常重要,不管是否设置了特定的样式值。如果暂时替换样式设置,则将其还原到原来的"not“状态,确保单元格将返回到从更高级别继承样式设置。

唉,这似乎行不通:

代码语言:javascript
复制
DataGridViewCell cell = ...;

Debug.Assert(!cell.HasStyle);           // cell is not using its own style
var cachedColor = cell.Style.ForeColor; // cache the original color
cell.Style.ForeColor = Color.Red;       // indicate a change
Debug.Assert(cell.HasStyle);            // now cell is using its own style

// restore to the 'not set' state:
cell.Style.ForeColor = cachedColor;
Debug.Assert(!cell.HasStyle);           // exception, not using inherited style
cell.Style = cell.InheritedStyle;       // try other method to restore
Debug.Assert(!cell.HasStyle);           // still exception

所以问:如何将样式设置恢复到它原来的"not“状态?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-04-11 12:15:18

看来我对Cell.Style和Cell.InheritedStyle完全误解了。

我认为继承的样式是从行/交替行/ DataGridView继承的样式,而样式是由此产生的样式。

不!

结果样式是DataGridViewCell.InheritedStyle。这个样式等于DataGridViewCell.Style,或者如果它有一个空值,它就等于DataGridViewRow.InheritedStyle的样式,这反过来等于DataGridViewRow.DefaultStyle的值,或者如果它是null,DataGridView.AlternatingRowsDefaultCellStyle等等。

因此,要知道实际使用的是哪种样式,请获取DataGridViewCell.InheritedStyle,以指定特定的样式,更改DataGridViewCell.Style的属性,当您得到它时,该属性将自动创建并填充继承的值。

若要丢弃DataGridViewCell.Style,只需将其设置为空。在此之后,DataGridViewCell.HasStyle将为false,而DataGridViewCell.InheritedStyle将是从交替行/所有行继承的样式。

示例:-按钮“更改”将当前单元格的前颜色更改为红色,完整行的BackColor更改为AliceBlue --按钮“丢弃”将恢复到默认的单元格样式。

代码语言:javascript
复制
private void buttonChange_Click(object sender, EventArgs e)
{
    DataGridViewCell cell = this.dataGridView1.CurrentCell;
    DataGridViewRow row = cell.OwningRow;

    if (!row.HasDefaultCellStyle)
    {
        row.DefaultCellStyle.BackColor = Color.AliceBlue;
    }

    if (!cell.HasStyle)
    {
        cell.Style.ForeColor = Color.Red;
    }
}

结果:当前单元格显示为红色前景色,当前行显示为AliceBlue背景色。

代码语言:javascript
复制
private void buttonDiscard_Click(object sender, EventArgs e)
{
    DataGridViewCell cell = this.dataGridView1.CurrentCell;
    DataGridViewRow row = cell.OwningRow;

    if (row.HasDefaultCellStyle)
    {
        row.DefaultCellStyle = null;
        Debug.Assert(!row.HasDefaultCellStyle);
    }
    if (cell.HasStyle)
    {
        cell.Style = null;
        Debug.WriteLine(!cell.HasStyle);
    }   
}

结果:当前单元格和当前行显示了它们的原始颜色。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36545774

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档