【问题标题】:Editing dIfferent types of objects using different controls in Wpf Datagrid Column使用 Wpf Datagrid Column 中的不同控件编辑不同类型的对象
【发布时间】:2015-10-25 07:18:44
【问题描述】:

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

并且需要动态填充。

我正试图从上周开始弄清楚,但这很难。

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

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

我会感激每一个提示。

谢谢

【问题讨论】:

  • 如果你像你说的那样使用字典,你只能有1行数据......?除非你建议收藏字典!?
  • 是的,你说得对,我收藏了字典。谢谢格伦
  • 有必要吗?不知道编译时会有哪些列?
  • 两列:属性名称和属性值。从这个字典集合中填充

标签: c# wpf xaml datagrid


【解决方案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>

结果:

【讨论】:

  • 感谢 jstreet 的回答,但在这种方法中,我想我希望能够编辑这些值。我只能在屏幕上显示它们。
  • 事实上,您已经可以编辑所有内置类型,如字符串、int、bool、double,可能还有枚举(没有尝试)。对于任何自定义类,例如 MyCustomClass,您都可以使用 PropertyGrid。
猜你喜欢
  • 2011-03-17
  • 2011-06-26
  • 2011-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-07
相关资源
最近更新 更多