【问题标题】:DataBinding a DataGridview rows BackColorDataBinding DataGridview 行 BackColor
【发布时间】:2009-04-23 12:54:02
【问题描述】:

我有一个使用数据绑定的 DataGridView,带有手动创建的列,这很好用。

但是,我也希望行的 BackColor 也是数据绑定的,但到目前为止,我的尝试都遇到了错误。

这是我最近的尝试:

dataGridFileTransfer.RowHeadersVisible = false;
dataGridFileTransfer.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridFileTransfer.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridFileTransfer.MultiSelect = false;
dataGridFileTransfer.ReadOnly = true;
var files = GetReceivedFiles(false).Union(FileDetails.Select(FileStatus.FailedVerification)).ToList();
dataGridFileTransfer.AutoGenerateColumns = false;

string[] displayHeaders = new string[] { COL_NAME, COL_TYPE, COL_CREATED, COL_SIZE, COL_STATUS };
string[] displayProps = new string[] { "Filename", "FileTypeDisplayName", "Created", "Size", "FileStatus" };

for (int i = 0; i < displayHeaders.Length; i++)
{
  DataGridViewTextBoxColumn col = new DataGridViewTextBoxColumn();
  col.HeaderText = displayHeaders[i];
  col.DataPropertyName = displayProps[i];

  if (displayHeaders[i] == COL_CREATED)
    col.DefaultCellStyle.Format = Constants.DDMMYYYHHMMSS;

  dataGridFileTransfer.Columns.Add(col);
}

Binding bi = new Binding("DefaultCellStyle.BackColor", files, "DisplayColor");
dataGridFileTransfer.DataBindings.Add(bi);

dataGridFileTransfer.DataSource = files;

正在生成 ArguementException:

"无法绑定到属性 上的“DefaultCellStyle.BackColor” 目标控制。参数名称: 属性名"

是 PropertyName 的值错误,还是应该绑定到 DataGridView 以外的对象? (即一列?) 还是 PropertyName 不能是 X.Y 形式的问题?我以为我以前见过/使用过这种语法,但也许它只适用于 DataMember?

非常感谢任何帮助

【问题讨论】:

    标签: c# winforms data-binding datagridview


    【解决方案1】:

    我认为问题出在files.DisplayColorfiles 是一个集合,没有属性 DisplayColor 但集合的每个项目都有。所以你试图绑定一个不存在的属性。进一步的绑定集合DataGridView.DataBindings 允许您数据绑定控件的属性,而不是其行。所有行只有一个DataGridView.DefaultCellStyle.BackColor。所以我相信你最终需要将每行的DefaultCellStyle 绑定到files 的对应项目,我不确定这是否可能。 DataGridView 可能会根据需要创建和删除行 - 例如,如果您执行过滤 - 这也会破坏数据绑定。

    所以,我不确定行着色是否可以通过数据绑定完成,但我个人对此表示怀疑。这将需要一些非常智能的逻辑来识别“将绑定到该行的对象数据的属性DisplayColor 绑定到该行的属性DefaultCellStyle.BackColor。”

    您完全可以实现这样的智能数据绑定。虽然这将是一件很棒的事情,但它也会非常复杂。作为一个简单的解决方案,您可以使用 RowPrepaint 事件为行设置正确的颜色。

    【讨论】:

    • 嗨,我只是想指出前两句话是不正确的,但我同意其他所有内容。最后我选择了 RowPrepaint。谢谢你的帮助。绑定时,数据源(文件)可以是一个集合,数据绑定属性将来自该集合中的活动对象(并且 files[0].DisplayColor 基于我的对象有效)。我已经在另一种形式上使用了这种方法。即 txtServerAddress.DataBindings.Add("Text", m_Profiles, "ServerAddress");将 txtServerAddress.Text 绑定到活动的 Profile.ServerAddress 值。
    猜你喜欢
    • 2012-12-30
    • 2018-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-10
    • 2015-01-31
    • 2013-06-12
    相关资源
    最近更新 更多