用于在数据网格中绑定的多个 属性 类型

Multiple property type for binding in data grid

我有一个数据网格,因此我想为不同类型的 类 获取数据。就像根据特定条件,我想将数据网格与类型为 int 的 Observable 集合绑定,在某些情况下,它将是类型为字符串的 Observable 集合。我想使用 MVVM 架构,所以我不想使用代码隐藏文件。是否可以定义 Observable 集合的 属性 如下:

ObservableCollection<object> PropertyName { get; set; }

在这种情况下使用它是否正确?

Create a data model, for instance

public class User
{
    public string Name { get; set; }
    public int Age { get; set; }
}

Then the 属性 would be

public ObservableCollection<User> Users { get; set; }

DataGrid will automatically generate a column for the each data item 属性.

<DataGrid ItemsSource="{Binding Users}"/>

But you can manually create and bind columns to properties in XAML

Don't forget to propertly set the DataContext which must be set to ViewModel's instance.