c# listview怎樣簡(jiǎn)化代碼

c#
小樊
81
2024-11-15 13:44:58
欄目: 編程語言

在C#中,為了簡(jiǎn)化ListView的代碼,您可以使用以下方法:

  1. 使用LINQ查詢來填充ListView的數(shù)據(jù)。這樣可以減少循環(huán)和條件語句的數(shù)量,使代碼更加簡(jiǎn)潔。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

public class ListViewExample : Form
{
    private ListView listView;
    private List<Person> people;

    public ListViewExample()
    {
        listView = new ListView();
        listView.Dock = DockStyle.Fill;
        listView.Columns.Add("Name", 100);
        listView.Columns.Add("Age", 50);

        people = new List<Person>
        {
            new Person { Name = "Alice", Age = 30 },
            new Person { Name = "Bob", Age = 25 },
            new Person { Name = "Charlie", Age = 35 }
        };

        listView.Items.AddRange(people.Select(p => new ListViewItem(new[] { p.Name, p.Age.ToString() })).ToArray());

        this.Controls.Add(listView);
    }

    public static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new ListViewExample());
    }
}

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}
  1. 使用數(shù)據(jù)綁定來填充ListView的數(shù)據(jù)。這樣可以進(jìn)一步減少代碼量,使代碼更加簡(jiǎn)潔。
using System;
using System.Collections.ObjectModel;
using System.Windows.Forms;

public class ListViewExample : Form
{
    private ListView listView;
    private ObservableCollection<Person> people;

    public ListViewExample()
    {
        listView = new ListView();
        listView.Dock = DockStyle.Fill;
        listView.Columns.Add("Name", 100);
        listView.Columns.Add("Age", 50);

        people = new ObservableCollection<Person>
        {
            new Person { Name = "Alice", Age = 30 },
            new Person { Name = "Bob", Age = 25 },
            new Person { Name = "Charlie", Age = 35 }
        };

        listView.ItemsSource = people;

        this.Controls.Add(listView);
    }

    public static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new ListViewExample());
    }
}

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

這兩種方法都可以簡(jiǎn)化ListView的代碼,使代碼更加簡(jiǎn)潔和易于維護(hù)。

0