【问题标题】:How to edit the cell type in a DataGrid Control wpf?如何在 DataGrid 控件 wpf 中编辑单元格类型?
【发布时间】:2016-06-15 02:09:35
【问题描述】:

在我的应用程序中,我有一个 Server 类,它具有公共属性 NameConnected

Connected 是一个布尔值,由Server 类的每个实例更新。

现在我有DataGrid,它正在从称为服务器的服务器列表中自动生成列。

有没有办法更改 dataGrid,使其在 Connected 为真时显示“已连接”,而在 Connected 为假时显示“已断开”?

【问题讨论】:

  • 数据网格控件,编辑了我的帖子以反映这一点。对混淆表示歉意。
  • 绝对需要autogenerating columns 吗?在 xaml 中定义 2 列可能更简单

标签: c# wpf datagrid


【解决方案1】:

如果使用AutoGenerateColumns,则可以在后面的代码中处理AutoGeneratingColumn事件并修改新创建的ConnectedDataGridCheckBoxColumn。我要做的是创建一个触发器,它将根据 ChechBox 检查状态更改状态文本:

private void DataGridAutoGeneratingColumnHandler(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
    if (e.PropertyName == "Connected")
    {
        var c = e.Column as DataGridCheckBoxColumn;
        if (c == null)
            return;
        c.IsReadOnly = true;
        c.ElementStyle =
            new Style
            {
                TargetType = typeof (CheckBox),
                Setters =
                {
                    new Setter { Property = ContentProperty, Value = "Disconnected" },
                    // prevent checking CheckBoxes 
                    new Setter { Property = IsHitTestVisibleProperty, Value = false },
                },
                Triggers =
                {
                    new Trigger
                    {                                
                        Property = CheckBox.IsCheckedProperty, 
                        Value = true,
                        Setters =
                        {
                            new Setter { Property = ContentProperty, Value = "Connected" }
                        }
                    }
                }
            };
    }
}


另一个想法:在 viewModel 中创建一个特殊的属性来描述连接状态。
public class Server
{
    public string Name { get; set; }

    public bool Connected { get; set; }

    public string ConnectionStatus
    {
        get { return Connected ? "Connected" : "Disconnected"; }
    }
}

然后禁用Connected 属性的列生成

private void DataGrid_AutoGeneratingColumnHandler(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
    if (e.PropertyName == "Connected")
        e.Cancel = true;
}

【讨论】:

  • 感谢您的详细回复!
猜你喜欢
  • 2012-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-27
  • 1970-01-01
  • 1970-01-01
  • 2011-10-09
相关资源
最近更新 更多