如何使用绑定和数据模板使WPF DataGrid显示ViewModel集合

5
首先,我想道歉,因为我相信这个问题的答案非常简单。但是,我仍然无法找到答案。
这是我使用WPF的第一周。我只是希望在DataGrid中显示某种列表的内容。我目前正在尝试使用ObservableCollection<>和DataGrid,但这可能会改变。如何对列表进行DataTemplate处理并显示它?
该列表位于ViewModel中,并已在Apps.xaml.cs中设置为MainWindow.xaml的数据源:
protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);

    var window = new MainWindow();

    // Create the ViewModel to which 
    // the main window binds.
    var viewModel = new MainWindowViewModel();

    // Allow all controls in the window to 
    // bind to the ViewModel by setting the 
    // DataContext, which propagates down 
    // the element tree.
    window.DataContext = viewModel;

    window.Show();
}

以下是当前列表:

    public ObservableCollection<PersonData> SearchResults { get; set; }

对于我的xaml而言,我相当茫然——我尝试了绑定和ItemsSource的摆弄,但实际上我并不知道如何在这里使用它们。此外,我想使用DataTemplate是必要的,因为我需要让它知道列需要显示PersonData的某些属性,例如名字、姓氏、位置和职位。如果有帮助,非常感谢。
编辑
更一般地说,如何简单地显示ViewModel列表、集合或任何其他东西?
2个回答

12

您的基本DataGrid语法应该如下所示:

<DataGrid ItemsSource="{Binding SearchResults}"
          AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn Header="First Name"  Binding="{Binding FirstName}"/>
        <DataGridTextColumn Header="Last Name" Binding="{Binding LastName}" />
    </DataGrid.Columns>
</DataGrid>
如果您不想在 DataGrid 中显示数据,则可以使用一个 ItemsControl
默认的 ItemsControl 会将所有项目添加到一个 StackPanel 中,并使用绑定到项目的 .ToString()TextBlock 来绘制每个项目。您可以通过为其指定自己的 ItemsPanelTemplateItemTemplate 来更改 ItemsControl 显示项目的方式。了解一些示例,请查看我在 WPF's ItemsControl 上的博客文章:my blog post on WPF's ItemsControl

谢谢,但似乎我的程序决定要恨我。我试着简化它,将搜索结果转换为字符串集合,就像你博客中的示例一样,并使用了第一个ItemsControl示例; 但什么也没有显示出来。 - Bondolin
@NathanBond 看起来 DataContext 没有正确设置,或者你的 SearchResults 集合没有触发 PropertyChanged 通知。我建议使用 Snoop 工具来帮助调试问题。 - Rachel
是的,我发现我忘记包括 INotifyPropertyChanged 接口了。谢谢你的帮助。 - Bondolin

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接