Bon*_*lin 3 wpf datagrid datatemplate observablecollection mvvm
首先,道歉,因为我确信这是问题的答案很简单.尽管如此,我似乎仍无法找到答案.
这是我使用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();
}
Run Code Online (Sandbox Code Playgroud)
这是当前列表:
public ObservableCollection<PersonData> SearchResults { get; set; }
Run Code Online (Sandbox Code Playgroud)
至于我的xaml,我相当迷失 - 我试图摆弄绑定和ItemsSource,并且真的不知道如何在这里使用它们.另外,我认为使用DataTemplate是必要的,因为我需要让它知道列需要显示PersonData的某些属性,例如名字和姓氏,位置和标题.任何帮助表示赞赏.
编辑
更一般地说 - 如何只显示一个ViewModel列表,集合,你有什么,期间?
Rac*_*hel 10
您的基本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>
Run Code Online (Sandbox Code Playgroud)
如果您不想在a中显示数据DataGrid,可以使用ItemsControl.
默认情况下ItemsControl会将所有项目添加到a中StackPanel,并使用TextBlock绑定到.ToString()项目的每个项目绘制每个项目.您可以ItemsControl通过指定项目ItemsPanelTemplate以及ItemTemplate使用它来更改项目的显示方式.有关示例,请查看我在WPF的ItemsControl上的博客文章.
阿赫。预习失败是致命的——我没有实现INotifyPropertyChanged。在这里找到了如何操作:http://msdn.microsoft.com/en-us/library/ms743695