5

首先,道歉,因为我确信这是问题的答案非常简单。尽管如此,我似乎仍然找不到答案。

这是我使用 WPF 的第一周。我只是希望在 DataGrid 中显示某种列表的内容。我目前正在尝试使用 ObservableCollection<> 和 DataGrid,但这可能会改变。如何 DataTemplate 列表并显示它?

该列表位于 ViewModel 中,该 ViewModel 已在 Apps.xaml.cs 中设置为 MainWindow.xaml 的 DataSource:

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 列表、集合、你有什么、句号?

4

2 回答 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会将所有项目添加到 aStackPanel中,并使用TextBlock绑定到项目的来绘制每个.ToString()项目。您可以ItemsControl通过指定您自己的项目ItemsPanelTemplateItemTemplate供其使用来更改项目的显示方式。对于一些示例,请查看我关于 WPF 的 ItemsControl 的博客文章

于 2012-07-06T19:55:40.327 回答
1

啊。预习失败是致命的——我没有实现 INotifyPropertyChanged。了解如何在这里:http: //msdn.microsoft.com/en-us/library/ms743695

于 2012-07-09T14:04:30.637 回答