【问题标题】:How to make a WPF DataGrid display a ViewModel collection with binding and a DataTemplate如何使 WPF DataGrid 显示具有绑定和 DataTemplate 的 ViewModel 集合
【发布时间】:2012-07-07 06:37:44
【问题描述】:

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

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

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

【问题讨论】:

    标签: wpf mvvm datagrid datatemplate observablecollection


    【解决方案1】:

    您的基本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

    【讨论】:

    • 谢谢,但我的程序似乎决心恨我。我继续尝试通过将搜索结果转换为您博客上的字符串集合来进行简化,并在那里使用了第一个 ItemsControl 示例;什么都没有显示。
    • @NathanBond 听起来DataContext 设置不正确,或者您的SearchResults 集合没有引发PropertyChanged 通知。我会推荐工具Snoop 来帮助调试问题
    • 是的,我发现我忘记包含 INotifiyPropertyChanged 接口。感谢您的帮助。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-10
      • 2017-04-18
      相关资源
      最近更新 更多