2012-07-06 17 views
3

首先,道歉,我相信这是问题的答案非常简单。尽管如此,我仍然无法找到答案。如何使WPF DataGrid显示具有绑定和DataTemplate的ViewModel集合

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

列表是在视图模型,已在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列表,收藏,你有什么,期?

回答

9

你的基本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显示项目的方式。对于一些示例,请查看my blog post on WPF's ItemsControl

+0

谢谢,但似乎我的计划是决心讨厌我。我继续尝试通过将搜索结果转换为您的博客中的字符串集合来简化,并且在那里使用了第一个ItemsControl示例;没有表现 – NargothBond 2012-07-06 20:34:25

+0

@NathanBond听起来好像DataContext没有正确设置,或者你的SearchResults集合没有引发PropertyChanged通知。我建议使用[Snoop]工具(http://snoopwpf.codeplex.com/)来帮助调试问题 – Rachel 2012-07-06 23:23:40

+0

是的,我发现我忘记了包含INotifiyPropertyChanged接口。感谢您的帮助。 – NargothBond 2012-07-09 14:03:30