带有列标题的gridview的viewmodel c#

时间:2011-12-05 05:48:45

标签: c# mvvm datatable data-annotations observablecollection

我需要一个解决方案。

我需要为网格视图创建一个视图模型。此视图模型应该是强类型的。恩。

List<Person> lstPersons=new List<Person>();
像这样的事情。另外,有了这个我应该能够有自定义列标题名称。我可以使用数据注释启用AutoGenerateColumns="True" 等,

class Person
{
      [DisplayName("Person Name")]
      public string name { get; set; }
}
像这样的事情。但我有两个问题。

  1. 我不知道如何在运行时更改此显示名称。

  2. 我正在使用telerik RADGridView。当我使用AutoGenerateColumns="True"ShowColumnFooters="True"时,整个用户界面都被卡住了。我认为这是telerik控件的错误。因此,我必须在XAML中定义所有列,并为每个列添加绑定路径。

  3. 无论如何,我认为这可以通过DataTable实现。但我觉得数据表是非常古老的结构和重物。

    如何创建Viewmodel来实现这一目标?有什么建议 ?

    随意提出任何问题。我不确定以上描述对每个人都很清楚。

3 个答案:

答案 0 :(得分:1)

试试这个discussion关于绑定列标题的数据。

答案 1 :(得分:1)

我假设你想要显示的列是固定的......所以你的ViewModel就像

 class MyViewModel
 {
      //Implement Properties nad proper binding in Xaml and INotifyPropertyChanged for every property that you need on View Level
      ObservableCollection<Persons> persons;
      string columnheader1;
      string columnheader2;
      string columnheader3;

 }

XAML

        <telerik:RadGridView.Columns> 

            <telerik:GridViewDataColumn   DataMemberBinding="{Binding UserName}" Width="200">

                <telerik:GridViewDataColumn.Header> 

                    <TextBlock Text="{Binding Columnheader1}"></TextBlock> 

                </telerik:GridViewDataColumn.Header> 

                </telerik:GridViewDataColumn> 

            <telerik:GridViewDataColumn Header="{Binding Columnheader2}" DataMemberBinding="{Binding IsOnline}" MinWidth="200" Width="*"/> 

            <telerik:GridViewDataColumn Header="{Binding Columnheader3}" DataMemberBinding="{Binding LastActivityDate}" MinWidth="200"/> 

        </telerik:RadGridView.Columns> 

这可能会成功..... :)

答案 2 :(得分:1)

您可以继续在模型上使用DisplayName属性,但正如您所指出的,无法在运行时更改它。为此,请在ViewModel中实现填充

的字典
public PeopleGridViewModel
{
    public ObservableCollection<Person> People;
    public Dictionary<string, string> PersonColumnHeaders;

    public PeopleGridViewModel()
    {
        // 1. write C# here to snag the property names from the typeof(Person)
        // 2. get the DisplayName attribute value for that property too.
        // 3. add the propertyName.ToString() and the DisplayName string to the dictionary as a key/value pair.

        // the result is you have a collection of column headers that start with the defaults from the propertys on the object... but they can be manipulated at run-time, and you don't havem them 100% hard typed like in adcool's example.
    }
}

我认为show column footers deal是你所建议的Telerik问题。