gpt4 book ai didi

wpf - 如何使 WPF DataGrid 显示具有绑定(bind)和 DataTemplate 的 ViewModel 集合

转载 作者:行者123 更新时间:2023-12-02 14:23:42 27 4
gpt4 key购买 nike

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

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

该列表位于 ViewModel 中,该 View 模型已在 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,我相当迷失——我尝试摆弄绑定(bind)和 ItemsSource,但真的不知道如何在这里使用它们。另外,我认为使用 DataTemplate 是必要的,因为我需要以某种方式让它知道列需要显示 PersonData 的某些属性,例如名字和姓氏、位置和标题。如有任何帮助,我们将不胜感激。

编辑

更一般地说——如何简单地显示 ViewModel 列表、集合,等等?

最佳答案

您的基本 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 中,并使用绑定(bind)到 TextBlock 绘制每个项目项目的.ToString()。您可以通过指定您自己的 ItemsPanelTemplateItemTemplate 来更改 ItemsControl 显示项目的方式。有关一些示例,请查看 my blog post on WPF's ItemsControl .

关于wpf - 如何使 WPF DataGrid 显示具有绑定(bind)和 DataTemplate 的 ViewModel 集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11368364/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com