windows8开发-关于ListBox中的Items元素

ListBox中的Items集合,是ItemsSource集合的映射。在API中是这么声明和定义的:

        //
        // 摘要:
        //     获取用于生成控件内容的集合。
        //
        // 返回结果:
        //     如果存在用于生成控件内容的集合,则为该集合;否则为 null。默认值为空集合。
        public ItemCollection Items { get; }

如果ListBox的ItemsSource是List<long>, 那么Items也就是List<long>类型;如果是ObservableCollection<someClassType>, 那Items也就是此类型集合。

通过Items,除了查看数据源的用途,还能做什么呢?下面将会讨论一下,关于使用Items在初始化ListBox时设置默认多项选择的状态的用法。

虽然是比较细小的功能,但是值得了解一下。以下是一个示例说明:

(1)首先创建ListBox的数据源,该数据源是类型为ListBoxItem的集合。

       List<ListBoxItem> items = new List<ListBoxItem>();
       for (int i=1; i<=12; ++i)
       {
          items.Add(new ListBoxItem() { Content = i });  // 实际用到的数据会是整型i, 包含在ListBox的Content中
       }
       MonthLB.ItemsSource = items;

(2)接着定义一个公有成员,设置get,set访问器,用于获取选中的ListBoxItem项和初始化设置被选中的项。

public List<int> SelectedMonths
        {
            get
            {
                List<int> months = new List<int>();
                foreach (ListBoxItem item in MonthLB.Items)
                {
                    if (item.IsSelected) // 该ListBoxItem为选中状态
                    {
                        months.Add((int)item.Content);
                    }
                }
                return months;
            }
            set
            {
                if (value == null || value.Count == 0)
                {
                    foreach (var item in MonthLB.Items)
                        (item as ListBoxItem).IsSelected = true;
                }
                else
                {               
		    if(value == null)
	            {
			MonthLB.ItemsSource = null;
			return;
	            }
                    foreach (var index in value)
                    {
                        if (index < 0) index = 0;
			// 设置该ListBoxItem的 IsSelected = true, 即为选中状态
                        (MonthLB.Items[index] as ListBoxItem).IsSelected = true;
                    }
                }
            }
        }

(3)ListBox的属性SelectionMode设置为复选状态,即SelectionMode="Multiple"。这样就可以实现ListBox的复选和初始化多选状态啦。

可能还有更好的办法,但我没找到;如果谁知道,please tell me。 ~_~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值