WPF:如何开始为使用 MVVM 构建的 DataGrid 设置样式?

标签 wpf mvvm datagrid styles observablecollection

我有一个名称列表,我想绑定(bind)到数据网格以进行编辑/排序/等。但是,我根本不喜欢 DataGrid 的显示方式。当我真的想要一个自定义顺序时,列按字母顺序排列(我希望我可以隐藏 ID 列,或者使该列不可编辑)。我不知道如何开始做这些......

注意:我删除了很多“通用”代码(例如:INotifyPropertyChanged 代码...)

//PersonModel.cs
public class PersonModel
{
    public Int32 ID { get; set; }
    public String FirstName { get; set; }
    public String LastName { get; set; }
}

//PersonViewModel.cs
public class PersonViewModel
{
    public PersonViewModel()
    {
        Init();
    }
    public PersonViewModel(ObservableCollection<PersonModel> persons)
    {
        Init(person);
    }
    private void Init(ObservableCollection<PersonModel> persons = null)
    {
        Persons = person ?? new ObservableCollection<PersonModel>();
    }

    public ObservableCollection<PersonModel> Persons { get; set; }
}

//PersonView.xaml
<UserControl ...

    ...

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

    ...
</UserControl>

最佳答案

除非您另有说明,否则 DataGrid 通过反射推断列。如果你想控制,你可以:

<DataGrid ItemsSource="{Binding Persons}">
    <DataGrid.Columns>
        <DataGridTextColumn Header="First Name" Binding="{Binding FirstName}"/>
        <DataGridTextColumn Header="Last Name" Binding="{Binding LastName}"/>
    </DataGrid.Columns>
</DataGrid>

关于WPF:如何开始为使用 MVVM 构建的 DataGrid 设置样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3566966/

相关文章:

c# - WPF 设计 : How to make User control with rounded corner and shadow effect

c# - 如何显示 Windows 图元文件?

wpf - 我可以在 View code behind 中使用 Unity CContainer 吗? (MVVM)

WPF 数据网格 : How do I databind the properties of the SelectedItem to trigger INotifyPropertyChangedEvents?

c# - 每个单元格中具有不同 UserControl 的 WPF DataGrid

wpf - 绑定(bind)已损坏但没有错误

c# - 检测 IME(输入法编辑器)是否在 Silverlight 中处于事件状态

wpf - MVVM gridview 绑定(bind)到数据表 WPF

c# - Datagrid 中的工具提示,从代码隐藏中添加

wpf - DataGrid 计算两个数据绑定(bind)单元格中值之间的差异