WPF简单实例,ListView数据绑定,CheckBox/Button删除操作

实现功能如下图,显示一个list的数据内容,并为每行添加checkbox复选框和单独按钮,来实现批量删除和单行删除.

数据源的结构非常简单,只有三个属性,分别是uid,username,password,分别对应用户id,用户名,密码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WPFGridView
{
    public class User
    {
        int uid;

        public int Uid
        {
            get { return uid; }
            set { uid = value; }
        }
        string username;

        public string Username
        {
            get { return username; }
            set { username = value; }
        }
        string password;

        public string Password
        {
            get { return password; }
            set { password = value; }
        }
    }
}


maiwindow界面,xaml代码如下

<Window x:Class="WPFGridView.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" mc:Ignorable="d" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" d:DesignHeight="600" d:DesignWidth="800" SizeToContent="WidthAndHeight">
    <Grid Name="grid">
        
        <ListView Height="303" HorizontalAlignment="Left" Name="listView1" VerticalAlignment="Top" Width="778" ItemsSource="{Binding Path=lists}">
            <ListView.View>
                <GridView>
                    <GridViewColumn x:Name="gvc">
                        <GridViewColumn.Header>
                            <CheckBox Click="CheckBox_Click_1">全选</CheckBox>
                        </GridViewColumn.Header>
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <CheckBox Click="CheckBox_Click" Tag="{Binding Path=Uid}"></CheckBox>
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                    <GridViewColumn Header="用户id" DisplayMemberBinding="{Binding Path=Uid}" />
                    <GridViewColumn Header="用户名" DisplayMemberBinding="{Binding Path=Username}" />
                    <GridViewColumn Header="密  码" DisplayMemberBinding="{Binding Path=Password}" />
                    <GridViewColumn Header="操作">
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <Button Content="删除"  Width="75" Height="23" Click="Button_Click" CommandParameter="{Binding Path=Uid}"/>
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                </GridView>
            </ListView.View>
        </ListView>
        <Grid Height="252" HorizontalAlignment="Left" Margin="0,309,0,0" Name="grid1" VerticalAlignment="Top" Width="778">
            <Button Content="删除" Height="23" HorizontalAlignment="Left" Margin="6,27,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
        </Grid>
        <Button Content="Button" Height="2" HorizontalAlignment="Left" Margin="29,9,0,0" Name="button2" VerticalAlignment="Top" Width="3" />
    </Grid>
</Window>

通过listview来进行绑定,建立自定义模板"gridview资源"来进行展示.



<Grid Name="grid">
<ListView Height="303" HorizontalAlignment="Left" Name="listView1" VerticalAlignment="Top" Width="778">
<ListView.View>
<GridView>
<GridViewColumn Header="用户id" DisplayMemberBinding="{Binding Path=Uid}" />
<GridViewColumn Header="用户名" DisplayMemberBinding="{Binding Path=Username}" />
<GridViewColumn Header="密  码" DisplayMemberBinding="{Binding Path=Password}" />
</GridView>
</ListView.View>
</ListView>
</Grid>

首先

<GridViewColumn Header="用户id" DisplayMemberBinding="{Binding Path=Uid}" />
<GridViewColumn Header="用户名" DisplayMemberBinding="{Binding Path=Username}" />
<GridViewColumn Header="密  码" DisplayMemberBinding="{Binding Path=Password}" />

分别绑定每列数据和列头名,DisplayMemberBinding属性指定数据的来源,这里绑定了"User"类的三个属性.

然后使用<GridViewColumn.CellTemplate><DataTemplate>来自定义模板,添加多选框checkbox和每行的删除按钮.

<GridViewColumn x:Name="gvc">
<GridViewColumn.Header>
<CheckBox Click="CheckBox_Click_1">全选</CheckBox>
</GridViewColumn.Header>
<GridViewColumn.CellTemplate>
<DataTemplate>
<CheckBox Click="CheckBox_Click" Tag="{Binding Path=Uid}"></CheckBox>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="操作">
<GridViewColumn.CellTemplate>
<DataTemplate>
<Button Content="删除"  Width="75" Height="23" Click="Button_Click" CommandParameter="{Binding Path=Uid}"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>

分别为checkbox和button按钮加上事件,为删除做准备.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WPFGridView
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private List<int> selectUid = new List<int>();//保存多选用户ID
        private List<int> allUid = new List<int>();//保存全选用户ID
        private List<User> list = new List<User>();//用户列表源数据
        

        public MainWindow()
        {
            InitializeComponent();
            this.DataBinding();
        }


        /// <summary>
        /// 列表数据初始化并绑定
        /// </summary>
        private void DataBinding()
        {
            for (int i = 0; i < 5; i++)
            {
                User user = new User()
                {
                    Uid = i + 1,
                    Username = "username" + i,
                    Password = "password"
                };
                list.Add(user);
            }
            this.listView1.ItemsSource = list;//为ListView绑定数据源
        }

        /// <summary>
        /// 复选框删除用户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            this.DeleteUsers(selectUid);
            this.listView1.Items.Refresh();//刷新数据
        }

        
        
        /// <summary>
        /// 由ChecBox的Click事件来记录被选中行的
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CheckBox_Click(object sender, RoutedEventArgs e)
        {
            CheckBox cb = sender as CheckBox;
            int uid = Convert.ToInt32(cb.Tag.ToString()); //获取该行id
            if (cb.IsChecked == true)
            {
                selectUid.Add(uid);  //如果选中就保存id
            }
            else
            {
                selectUid.Remove(uid);   //如果选中取消就删除里面的id
            }
        }

        /// <summary>
        /// 批量删除用户
        /// </summary>
        private void DeleteUsers(List<int> selectUid)
        {
            if (selectUid.Count > 0) 
            {
                foreach (var uid in selectUid)
                {
                    list.Remove(list[uid - 1]);
                }
            }
        }

        /// <summary>
        /// 按钮单行删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Button b = sender as Button;
            int uid = Convert.ToInt32(b.CommandParameter);
            this.DeleteUser(uid);
            this.listView1.Items.Refresh();
        }

        /// <summary>
        /// 删除一个用户
        /// </summary>
        /// <param name="uid"></param>
        private void DeleteUser(int uid)
        {
            list.Remove(list[uid - 1]);
        }

        /// <summary>
        /// 全选
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CheckBox_Click_1(object sender, RoutedEventArgs e)
        {
            CheckBox cb = sender as CheckBox;
            if (cb.IsChecked == true)
            {
                
                allUid = list.Select(l => l.Uid).ToList();
            }
            else
            {
                allUid.Clear();
            }
        }
    }
}

DataBinding()中,循环创建一个包含五个用户的集合,通过该集合为ListView绑定数据源,或者使用<ListView>标签中的ItemsSource="{Binding Path=list}"属性来达到绑定数据源的效果.


复选框的删除思路和按钮删除思路及代码编写方式相同,(复选框删除借鉴了WPF之DataGrid应用中的方法).

Button是通过CommandParameter属性,再使用{Binding Path=Uid}"绑定该行用户ID作为参数传给事件进行删除处理.

CheckBox同理,则是通过Tag属性绑定用户id,每次点击复选框通过判断选择状态IsChecked的值,来把该行用户id存入到记录已选择的用户id的集合中selectUid,最后调用DeleteUsers方法进行批量删除操作.


在学习使用CheckBox的过程中,还搜索到另一种方式获取CheckBox的值:给数据源对象添加一个bool值属性或其他类型如用int类型 0和1(这点利用了WPF的ListView数据绑定的模式Model:TwoWay,文本框和复选框的属性默认为TwoWay),然后遍历ListView.Items,通过True/False来判断该Item的CheckBox是否被选中,再进行相应的处理.不过,此实例并未采用该方法进行编码,因为设想实际项目中从数据库获取对应的数据实体,其后需要另外建立一个继承该实体的ViewModel,并添加判断CheckBox的自定义属性如:bool isEnable,再对该ViewModel进行赋值.这个过程则多了一个赋值过程,消耗了资源.(对于如何使用ViewModel和数据实体Model的认识本人还尚浅,希望各位阅读此文的朋友指点.)


    

  • 2
    点赞
  • 6
    评论
  • 4
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值