使用Wpf Datagrid列中的不同控件编辑不同类型的对象

时间:2015-08-03 08:43:18

标签: c# wpf xaml datagrid

我需要使用十二个字典从ObservableCollection创建Wpf Datagrid绑定,其中string是property的名称,object是属性值。每个对象可以是不同的类型,它可以是布尔(复选框),字符串(文本框),CustomClassObject(组合框或文本框),整数(文本框)或枚举(包含枚举中每个值的ComboBox)。

需要动态填充。

我试图从上周弄清楚它,但这很难。

您是否知道如何创建解决此问题的数据网格?如何将从字典或整个字典中提取的对象列表绑定到datagrid以允许用户轻松编辑它?

如果可能的话,我是否应该将datatemplate与某些转换器一起使用,这将返回右控制,并为每个对象提供相应的值。或者我应该创建usercontrol,它将包含可绑定属性对象,我将为每个值分配右控制完整字段,它将绑定到ContentControl?

我会感激每一个提示。

由于

1 个答案:

答案 0 :(得分:1)

也许是这样的:

public class MyObjectList : ObservableCollection<object>
{
    public MyObjectList()
    {
        Add(new KeyValuePair<string, int>("Key1", 1));
        Add(new KeyValuePair<string, string>("Key2", "Value2"));
        Add(new KeyValuePair<string, bool>("Key3", true));
        Add(new KeyValuePair<string, double>("Key4", 1.5));
        Add(new KeyValuePair<string, MyEnum>("Key5", MyEnum.OPTION3));
        Add(new KeyValuePair<string, MyCustomClass>("Key6", new MyCustomClass(123)));
    }
}

public class MyCustomClass
{
    int value;

    public MyCustomClass(int value)
    {
        this.value = value;
    }
    public override string ToString()
    {
        return string.Format("MyCustomClass is {0}", value);
    }
}

enum MyEnum { OPTION1, OPTION2, OPTION3 };

XAML:

    <DataGrid Margin="0" ItemsSource="{Binding Mode=OneWay}">
        <DataGrid.DataContext>
            <local:MyObjectList/>
        </DataGrid.DataContext>
    </DataGrid>

结果:

enter image description here