Why isn't my WPF Datagrid showing data?

后端 未结 5 2017
借酒劲吻你
借酒劲吻你 2020-12-16 21:49

This walkthrough says you can create a WPF datagrid in one line but doesn\'t give a full example.

So I created an example using a generic list and connected it to th

5条回答
  •  旧巷少年郎
    2020-12-16 22:25

    Typically in WPF, you would leverage an ObservableCollection<>

    Because then you can just .Add() / .Remove() elements to/from the source collection, and any controls bound (Data Binding) automatically get updated (Automatic Property Change Notification). Those are 2 important concepts in WPF.

    Main Window View Model

    using System.Collections.Generic;
    
    namespace TestDatagrid345.ViewModels
    {
      class Window1ViewModel
      {
        private ObservableCollection _customers = new ObservableCollection();
        public ObservableCollection Customers
        {
          Get { return _customers; }
        }
      }
    }
    

    Main Window

    using System.Collections.Generic;
    using System.Windows;
    
    namespace TestDatagrid345
    {
      public partial class Window1 : Window
      {
        Window1ViewModel _viewModel;
    
        public Window1()
        {
          InitializeComponent();
          _viewModel = (Window1ViewModel)this.DataContext; // @#$% (see XAML)
        }
    
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
          // but this stuff could instead be done on a 'Submit' button click on form:
          _viewModel.Customers.Add(new Customer { FirstName = "Tom", LastName = "Jones" });
          _viewModel.Customers.Add(new Customer { FirstName = "Joe", LastName = "Thompson" });
          _viewModel.Customers.Add(new Customer { FirstName = "Jill", LastName = "Smith" });
        }
      }
    }
    

    Main Window XAML

    
      
         
      
      
       
      
    
    

提交回复
热议问题