ListBoxコントロールにデータをバインディングする - ObservableCollection継承クラスをバインディングする - WPF
ObservableCollectionクラスを継承したクラスをコントロールにバインディングする方法を紹介します。
UI
WPFアプリケーションを新規作成します。プロジェクト名は"WpfBinding2"としました。プロジェクトの作成後、メインフォーム(MainWindow.xaml)にListBoxを貼り付けます。
コード
以下のコードを記述します。
MainWindow.xaml
<Window x:Class="WpfBinding2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:src="clr-namespace:WpfBinding2"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<ObjectDataProvider x:Key="myBirds01" ObjectType="{x:Type src:Birds}"/>
</Window.Resources>
<Grid>
<ListBox Height="180" HorizontalAlignment="Left" Margin="12,12,0,0" Name="listBox1"
VerticalAlignment="Top" Width="259"
ItemsSource="{Binding Source={StaticResource myBirds01}}" />
</Grid>
</Window>
解説
<Window.Resources>
<ObjectDataProvider x:Key="myBirds01" ObjectType="{x:Type src:Birds}"/>
</Window.Resources>
部分で、ObjectDataProvider を定義します。x:Keyにはキー名を入力します。(任意の名前です)
ObjectTypeは"{x:Type src:Birds}"を入力しています。src:の後にObservableCollectionを継承したクラスのクラス名を入力します。
Birds.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
namespace WpfBinding2
{
public class Birds : ObservableCollection<string>
{
public Birds()
{
this.Add("Penguin");
this.Add("Owl");
this.Add("Falcon");
}
}
}
解説
public class Birds : ObservableCollection<string>
により、ObservableCollectionクラスからの派生クラスを定義します。
public Birds()
{
this.Add("Penguin");
this.Add("Owl");
this.Add("Falcon");
}
コンストラクタでAddメソッドを呼び出し要素を追加します。
実行結果
アプリケーションを実行すると下図の画面が表示されます。
一度アプリケーションを実行すると、デザイン画面にも反映されます。
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2017-09-04
作成日: 2012-03-08