---
title: "windows8开发-关于ListBox中的Items元素"
author: "mmdev"
date: "2012-12-19T21:01:00Z"
tags: []
slug: "windows8-listbox-items"
draft: false
lastmod: "2013-01-05T09:21:24Z"
id: 1759983
url: "https://mmdev.iteye.com/blog/1759983"
---

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

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

如果ListBox的ItemsSource是List&lt;long&gt;, 那么Items也就是List&lt;long&gt;类型；如果是ObservableCollection&lt;someClassType&gt;, 那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。 ~\_~