WPF - DataGrid 将列绑定到方法而不是 属性

WPF - DataGrid bind column to method instead of property

我有一个 class 表示一个顶点,它可以有多个属性。每个属性都由其名称标识。

public class Vertex
{
    private Dictionary<string, Attr> attributes;

    public Attr GetAttributeByName(string attributeName)
    {
        Attr attribute;
        if (attributes.TryGetValue(attributeName, out attribute))
        {
            return attribute;
        }

        return null;
    }
}

我想要一个 DataGrid 将其 ItemsSource 绑定到某些 ObservableCollection<Vertex>。每列应代表顶点的一个属性。我想在运行时控制列(添加新列或删除旧列)。但我无法做到这一点,因为新的列绑定需要 属性 的名称,它将从中获取单元格数据。但是我需要绑定以使用属性名称调用方法 GetAttributeByName() 来获取数据,而不仅仅是获取 属性。

string newAttributeName = "some_name";
DataGridTextColumn newColumn = new DataGridTextColumn();
newColumn.Header = newAttributeName;
newColumn.Binding = ???;

dataGrid.Columns.Add(newColumn);

有什么办法吗?

Is there some way to do it?

不,您不能真正绑定到这样的方法。

但是如果您将 Dictionary<string, Attr> 公开为 Vertex class 的 public 属性,您应该能够绑定到这个:

string newAttributeName = "some_name";
DataGridTextColumn newColumn = new DataGridTextColumn();
newColumn.Header = newAttributeName;
newColumn.Binding = new Binding($"Attributes[{newAttributeName}]");