2013年5月6日月曜日

ItemsControlとObservableCollectionによる表示

ListViewなど複数のデータを表示する場合、DataSourceとしてObservableCollectionを使うとデータに変化があった場合にView側に通知されるので便利なようです。

まずは簡単な使い方から試していこうかと思います

以下の例は
- ViewModel側でObservableCollectionであるPeopleを初期化
- View側は↑をItemsSourceとしてDataBindし、ListBox.ItemTemplateで単一データを表示
- 選択状態は SelctedItemでDataBind
という感じの動作(というか表示)としています

今回はDataContextをコードビハインドで行わずにxamlで書いています
(これでもOKのようなので)

--- MainWindowViewModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Practices.Prism.ViewModel;

using System.Collections.ObjectModel;
using System.Windows;


namespace ListViewTest_130430
{
    public class MainWindowViewModel
    {
        ObservableCollection<Person> _people = new ObservableCollection<Person>();
        public ObservableCollection<Person> People {
                    get { return _people; }
                    set { _people = value; }
        }

        /// <summary>
        /// コンストラクタ
        /// </summary>
        public MainWindowViewModel()
        {
            // 表示データの生成
            ObservableCollection<Person> people = new ObservableCollection<Person>();
            string[] names = new string[]{ "Stan Hansen", "Bruiser Brody", "Terry Funck", "Dick Murdoch"};
            foreach (string name in names)
            {
                Person p = new Person();
                p.Name = name;
                _people.Add(p);
            }
        }

        /// <summary>
        /// 選択されている人
        /// </summary>
        public Person SelectedPerson { get; set; }

        public void Execute()
        {
            if (SelectedPerson != null)
            {
                MessageBox.Show(SelectedPerson.Name);
            }
            else
            {
                MessageBox.Show("選択されていてません");
            }
        }
    }

    // ListBoxに表示するデータ
    public class Person
    {
        public string Name { get; set; }
    }
}


--- MainWindow.xaml
<Window x:Class="ListViewTest_130430.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:l="clr-namespace:ListViewTest_130430"
        Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <l:MainWindowViewModel />
    </Window.DataContext>
    <Grid>
        <ListBox x:Name="listBox1"
                 ItemsSource="{Binding People}"
                 SelectedItem="{Binding SelectedPerson}" >
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <ContentControl Content="{Binding Name}">
                    </ContentControl>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
</Window>

0 件のコメント:

コメントを投稿