本文共 2416 字,大约阅读时间需要 8 分钟。
ListView 控件的 SelectedItems 属性是操作 ListView 组件时非常实用的属性,用于获取用户选定的列表项集合。本文将通过 C# 代码示例,展示如何在 Windows 弹性应用程序中使用该属性并结合事件处理程序实现计算功能。
代码结构如下:
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;namespace Demo08{ public partial class MainForm : Form { public MainForm() { InitializeComponent(); } ////// 初始化列表中的数据。 /// /// /// private void MainForm_Load(object sender, EventArgs e) { string[] FoodList = new string[] { "Juice", "Coffee", "Cereal & Milk", "Fruit Plate", "Toast & Jelly", "Bagel & Cream Cheese" }; string[] FoodPrice = new string[] { "1.09", "1.09", "2.19", "2.49", "1.49", "1.49" }; this.BreakfastListView.BeginUpdate(); for (int Index = 0; Index < FoodList.Length; Index++) { ListViewItem Item = new ListViewItem(); Item.Text = FoodList[Index]; Item.SubItems.Add(FoodPrice[Index]); this.BreakfastListView.Items.Add(Item); } this.BreakfastListView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize); this.BreakfastListView.EndUpdate(); } ////// 计算用户选中的早餐所需的花费。 /// /// /// private void CalculateButton_Click(object sender, EventArgs e) { double Price = 0; ListView.SelectedListViewItemCollection SelectedItems = this.BreakfastListView.SelectedItems; foreach (ListViewItem Item in SelectedItems) { double ItemPrice = double.Parse(Item.SubItems[1].Text); Price += ItemPrice; } MessageBox.Show(string.Format("所选中的早餐需要花费{0}人民币!", Price)); } }}
代码解释:
Data Source Initialization:
Loading Data to ListView:
BeginUpdate
方法避免刷新 UI。ListViewItem
。Resizing Columns:
Calculating Total Cost:
LVQ SelectedItems
获取用户选定的项目集合。整个代码框架清晰易懂,适合后台管理或用户交互相关的应用场景。通过实际操作可以快速实现类似功能。
项目中使用的关键技术包括:
总体来说,这段代码展示了如何利用 ListView 组件与事件处理机制,实现用户交互和数据计算结合的应用场景。
转载地址:http://ldtiz.baihongyu.com/