WPF 使用CheckBox实现联动——全选和反选

来源:互联网 发布:c语言开根号的函数 编辑:程序博客网 时间:2024/06/14 04:15

XAML前端代码:

<Window x:Class="Treeview.MainWindow"        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"        xmlns:c="clr-namespace:Treeview"        Title="MainWindow" Height="350" Width="525">    <TreeView Name="tv" Width="170" Height="800" MaxHeight="520" BorderThickness="0">        <TreeView.ItemTemplate>            <HierarchicalDataTemplate DataType="{x:Type c:TreeCategory}"  ItemsSource="{Binding Children}">                <StackPanel  Margin="-2,0,0,0" Orientation="Horizontal" x:Name="staTree">                    <CheckBox x:Name="checkBox" Tag="{Binding Id}" IsChecked="{Binding IsSelected}" HorizontalAlignment="Center" VerticalAlignment="Center" Checked="CheckBox_Checked" Unchecked="checkBox_Unchecked" />                    <Image Source="{Binding Icon}" Height="20" Width="20" Margin="5"/>                    <TextBlock Text="{Binding Title}" FontSize="14" FontFamily="微软雅黑" HorizontalAlignment="Center" VerticalAlignment="Center"/>                </StackPanel>            </HierarchicalDataTemplate>        </TreeView.ItemTemplate>    </TreeView></Window>

ReportCategoryEntity类

public class ReportCategoryEntity
    {        public int Id { get; set; }        /// <summary>        /// 名称        /// </summary>        public string Title { get; set; }        /// <summary>        ///父节点        /// </summary>        public int ParentID { get; set; }        public ObservableCollection<TreeCategory> Children { get; set; }        public TreeCategory Parent { get; set; }        public string Icon { get; set; }        public ReportCategoryEntity()        {            this.Icon = @"\Images\Directory.png";            this.Children = new ObservableCollection<TreeCategory>();        }    }

TreeCategory 类,实现INotifyPropertyChanged接口

public class TreeCategory : INotifyPropertyChanged    {        private ObservableCollection<TreeCategory> children = new ObservableCollection<TreeCategory>();        public TreeCategory() { }        public TreeCategory(ObservableCollection<ReportCategoryEntity> totalCategory, int parentID)  //0  根目录        {            //第一步:选择根节点            foreach (ReportCategoryEntity item in totalCategory.Where(p => p.ParentID == 0))            {                TreeCategory tc = new TreeCategory();                tc.id = item.Id;                tc.parentID = item.ParentID;                tc.title = item.Title;                tc.icon = @"\Images\Folders_Down.png";                children.Add(tc);            }            //第二步:为每个子节点找到对应的父亲            foreach (ReportCategoryEntity item in totalCategory.Where(p => p.ParentID != 0))            {                Find_item(children, item);                if (item.Children.Count == 0)                {                    item.Icon = @"\Images\Directory.png";                }            }                   }        //子级递归        private void Find_item(ObservableCollection<TreeCategory> _list, ReportCategoryEntity _item)        {            foreach (TreeCategory item in _list)            {                if (item.Id == _item.ParentID)                {                    TreeCategory tc = new TreeCategory();                    tc.id = _item.Id;                    tc.parentID = _item.ParentID;                    tc.title = _item.Title;                    tc.icon = _item.Icon;                    tc.parent = item;                    item.icon = @"\Images\Folders_Down.png";                    item.Children.Add(tc);                    return;                }                if(item.Children != null)                {                      Find_item(item.Children, _item);                }                            }        }        public ObservableCollection<TreeCategory> Children        {            get { return this.children; }        }        private int id;        public int Id        {            get { return id; }            set { id = value; }        }        private int parentID;        public int ParentID        {            get { return parentID; }            set { parentID = value; }        }        private string icon;        public string Icon        {            get { return icon; }            set { icon = value; }        }                private TreeCategory parent;        public TreeCategory Parent        {            get { return parent; }            set { parent = value; }        }        /// <summary>        /// 显示的名称        /// </summary>        private string title;        public string Title        {            get            {                return title;            }            set            {                title = value;                this.NotifyPropertyChanged("Title");            }        }        /// <summary>        /// 是否选中        /// </summary>        private bool isSelected = false;        public bool IsSelected        {            set            {                this.isSelected = value;                this.NotifyPropertyChanged("IsSelected");            }            get { return this.isSelected; }        }        public event PropertyChangedEventHandler PropertyChanged;        private void NotifyPropertyChanged(String info)        {            if (PropertyChanged != null)            {                PropertyChanged(this, new PropertyChangedEventArgs(info));            }        }    }

后台代码:

/// <summary>    /// MainWindow.xaml 的交互逻辑    /// </summary>    public partial class MainWindow : Window    {        private ObservableCollection<TreeCategory> collection = new ObservableCollection<TreeCategory>();        public MainWindow()        {            InitializeComponent();            //数据初始化            ObservableCollection<ReportCategoryEntity> ctagr = new ObservableCollection<ReportCategoryEntity>() {                 new ReportCategoryEntity(){Id = 1,Title = "Node1.",ParentID = 0},                new ReportCategoryEntity(){Id = 2,Title = "Node2.",ParentID = 0},                new ReportCategoryEntity(){Id = 3,Title = "Node3.",ParentID = 1},                new ReportCategoryEntity(){Id = 4,Title = "Node4.",ParentID = 3},                new ReportCategoryEntity(){Id = 5,Title = "Node5.",ParentID = 3},                new ReportCategoryEntity(){Id = 6,Title = "Node6.",ParentID = 4},                new ReportCategoryEntity(){Id = 7,Title = "Node7.",ParentID = 2},                new ReportCategoryEntity(){Id = 8,Title = "Node8.",ParentID = 7},                new ReportCategoryEntity(){Id = 9,Title = "Node9.",ParentID = 8}            };            TreeCategory tc = new TreeCategory(ctagr,0);            //数据绑定            collection=tc.Children;            tv.ItemsSource = collection;        }        /// <summary>        /// 选中事件        /// </summary>        /// <param name="sender"></param>        /// <param name="e"></param>        private void CheckBox_Checked(object sender, RoutedEventArgs e)        {            ObservableCollection<TreeCategory> ob_list = new ObservableCollection<TreeCategory>();            //将list转换成ObservableCollection            foreach (TreeCategory item in tv.Items)            {                ob_list.Add(item);            }            //遍历ob_list            foreach (var item in ob_list)            {                //递归CheckBox                foreach (var items in item.Children)                {                    FindChild(ob_list, true,"checked",0);                    }            }        }        /// <summary>        /// CheckBox绑定的ID泛型        /// </summary>        private List<int> list_id = new List<int>();        /// <summary>        /// 取消事件        /// </summary>        /// <param name="sender"></param>        /// <param name="e"></param>        private void checkBox_Unchecked(object sender, RoutedEventArgs e)        {            CheckBox dg = sender as CheckBox;            int checkBox_id =Convert.ToInt32(dg.Tag.ToString());            if (list_id.Count>0)            {                //清空集合                list_id.RemoveAt(0);            }            list_id.Add(checkBox_id);            ObservableCollection<TreeCategory> ob_list = new ObservableCollection<TreeCategory>();            //将list转换成ObservableCollection            foreach (TreeCategory item in tv.Items)            {                ob_list.Add(item);            }            //遍历ob_list            foreach (var item in ob_list)            {                //递归CheckBox                foreach (var items in item.Children)                {                    FindChild(ob_list, false, "Unchecked", list_id[0]);                }            }        }        public void FindChild(ObservableCollection<TreeCategory> list, bool flog, string type, int id)        {            foreach (TreeCategory item in list)            {                              //选中遍历                if (type=="checked")                {                    //判断是否选中                    if (item.IsSelected)                    {                        item.IsSelected = flog;                    }                    //判断是否有父级                    if (item.Parent!=null)                    {                        //如果有父级并且被选中,那么子级也被选中                        if (item.Parent.IsSelected)                        {                            item.IsSelected = flog;                        }                    }                                    }                else//取消遍历                {                    //判断是否有父级                    if (item.Parent != null)                    {                        //判断是父级编号是否与点击的编号相等                        if (item.Parent.Id == id)                        {                            item.IsSelected = flog;                        }                    }                                }                //查询子级                if (item.Children != null)                {                    FindChild(item.Children, flog, type, id);                }            }                    }    }



阅读全文
'); })();
0 0
原创粉丝点击
热门IT博客
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 对氨基苯甲酸的合成 甲酸钠ph值 泵甲酸钠 对硝基苯甲酸乙酯的制备 邻羟基苯甲酸苯酯 异维甲酸乳膏 苯甲酸基 邻乙氧基苯甲酸 苯甲酸钠 分析纯 苯甲酸重结晶步骤 十二烷基苯甲酸钠 苯甲酸溶解度曲线 n-甲基二硫代氨基甲酸钾 血清游离三碘甲状原氨酸 血清游离三碘甲状原氨酸偏低 基准邻苯二甲酸氢钾 4-溴邻苯二甲酸 甲醇是什么 苯甲醇 甲醇化学式 甲醇中毒 甲醇吧 甲醇汽车 甲醇2001 甲醇钠 甲醇股吧 甲醇危害 甲醇期货吧 甲醇用途 甲醇有毒吗 甲醇的危害 甲醇钠甲醇溶液 甲醇燃油 甲醇概念股 甲醇柴油 什么是甲醇 供应甲醇 甲醇行情 甲醇发动机 中国甲醇网 甲醇的价格