C# generate listview and fill data no xaml

FredGrit發表於2024-04-17
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApp59
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.WindowState = WindowState.Maximized;
            InitListView();
        }

        private void InitListView()
        {
            ListView lv = new ListView();
            GridView view = new GridView();
            var props=typeof(Book).GetProperties();
            for(int i=0;i<props.Length; i++)
            {
                GridViewColumn cn=new GridViewColumn();
                cn.DisplayMemberBinding = new Binding(props[i].Name);
                cn.Header = props[i].Name;
                view.Columns.Add(cn);
            } 

            lv.View = view;

            List<Book> booksList = new List<Book>();
            for(int i=0;i<100;i++)
            {
                booksList.Add(new Book()
                {
                    Id = i + 1,
                    ISBN = $"ISBN_{i + 1}",
                    Name = $"Name_{i + 1}",
                    Summary = $"Summary_{i + 1}",
                    Title = $"Title_{i + 1}",
                    Topic = $"Topic_{i + 1}"
                });
            }
            lv.ItemsSource = booksList;
            this.Content = lv;
        } 
    }

    public class Book
    {
        public int Id { get; set; }
        public string ISBN { get; set; }
        public string Name { get; set; }
        public string Summary { get; set; }
        public string Title { get; set; }
        public string Topic { get; set; }

        
    }
}

相關文章