wpf - 向 WPF DataGrid 添加不在集合中的额外列

标签 wpf binding datagrid datatable

我正在使用 DataGrid 控件来显示 DataTable 的内容。因此数据表设置为DataGrid的ItemsSource。

DataGrid 的以下列代表数据表的列:

类型、名称、域、子域

现在,称为“属性”的动态列应包含特定信息,具体取决于“类型”列的值。 像这样的事情:

switch (Type)
    case ABC:   content="row.Field1"
    case DEF:   content="row.Field2"
    case XYZ:   content="row.FieldX"

其中 Field1 .. FieldX 是数据表中的所有列。 我目前正在将 DataGrid 与 BindingListCollectionView 一起使用。 如果解决方案能够以此为基础,那就最好了。

我尝试使用多值绑定(bind)和多值转换器,但我希望有更多的自由度,而不必预先选择字段:

var bind = new MultiBinding();

bind.Bindings.Add(new Binding("Protocol"));
bind.Bindings.Add(new Binding("Path1"));
bind.Bindings.Add(new Binding("Path2"));
bind.Bindings.Add(new Binding("Path3"));
bind.Bindings.Add(new Binding("Path4"));

bind.Converter = _ConfigurationMultiValueConverter;

col.Binding = bind;

最佳答案

你可以使用类似的东西。当然这只是一个例子。

public class YourClass
{
    public YourType Protocol;
    public YourType2 Path1;
    public YourType3 Path2;
    public YourType4 Path3;
    public YourType5 Path4;
    public int ChooseExpression;
    public YourType6 Field1;
    public YourType7 Field3;
    public YourType8 FieldX;
}

然后在您的 DataGrid 中

<DataGrid Name="IfYouNeedAName" AutoGennerateColumn="False" ItemsSource={Binding YourClass} >
    <DataGrid.Columns>
        <DataGridTextColumn Header="ProtocolHeader" Binding={Binding Protocol} />
        <DataGridTextColumn Header="Path1Header" Binding={Binding Path1} />
        ...
        <DataGridTextColumn Header="TheChoosenOne" Binding={Binding YourClass, YourBindingConverer} />
    </DataGrid.Columns>
</DataGrid>

最后是转换器,继承自IValueConverter

public class YourBindingConverer : IValueConverter
{
    public object Convert(object value, Type targetType, 
        object parameter, CultureInfo culture)
    {
        switch(value.ChooseExpression)
            case 1: return Field1.ToString();
            case 2: return Field3.ToString();
            case 3: return FieldX.ToString();
        else
            return string.Empty;
        end;
    }

    public object ConvertBack(object value, Type targetType, 
        object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

我凭内存写的,因为我这里没有VS。但我认为,可能是这样的。 如果您有更多问题,请随时提问。

作为奖励,here对于值(value)转换器来说是一个很好的解决方案。

关于wpf - 向 WPF DataGrid 添加不在集合中的额外列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31563172/

相关文章:

c# - WPF应用程序框架IView问题

wpf - 确定谁在 WPF 窗口中有焦点

java - 在 JavaFX 中连接 View 和模型的主要方式是什么?

wpf - wpf 中的弹出窗口和切换按钮交互

c - 无堆栈 VM 实现会出现哪些 C 集成问题?

c# - 使用 DataGrid C# 更新数据库

c# - 使用 C# 和 WPF 更新 XML 文件

wpf - 如何将 bool 值绑定(bind)到wpf中的组合框

c# - 如何使用 MVVM 更新 Datagrid?

WPF 数据网格 : SelectionChanged event isn't raised when SelectionUnit ="Cell"