チュートリアル: WPF デザイナーによるデータ バインディングの作成
このチュートリアルでは、WPF Designer for Visual Studio を使用して、データをコントロールに接続するデータ バインディングを作成する方法について説明します。
このチュートリアルでは次のタスクを行います。
プロジェクトを作成する。
Student クラスと StudentList コレクションを作成する。
データ バインディングを介して StudentList コレクションを表示する ListBox コントロールを作成する。
ブール型プロパティの外観をカスタマイズするために、IValueConverter を使用するカスタムの DataTemplate を作成する。
タスクを終了すると、リスト ボックスが学生のリストにバインドされます。 リスト ボックス項目ごとに、学生が登録されているかどうかを示す色付けされた四角形が表示されます。
注意
データ ソースのデータにバインドするには、[データ ソース] ウィンドウを使用します。 詳細については、「Visual Studio でのデータへの WPF コントロールのバインド」を参照してください。
注意
実際に画面に表示されるダイアログ ボックスとメニュー コマンドは、アクティブな設定またはエディションによっては、ヘルプの説明と異なる場合があります。 設定を変更するには、[ツール] メニューの [設定のインポートとエクスポート] をクリックします。 詳細については、「設定の操作」を参照してください。
必須コンポーネント
このチュートリアルを実行するには、次のコンポーネントが必要です。
- Visual Studio 2010.
プロジェクトの作成
最初に、WPF アプリケーション プロジェクトを作成し、データ ソースを追加します。 データ ソースは、単純な Student クラスのインスタンスが含まれる ObservableCollection<T> です。 また、プロジェクトには、ListBox コントロールのスタイルを設定するために、IValueConverter とカスタムの DataTemplate が含まれます。
プロジェクトを作成するには
Visual Basic または Visual C# で、DataBindingDemo という名前の新しい WPF アプリケーション プロジェクトを作成します。 詳細については、「方法 : 新しい WPF アプリケーション プロジェクトを作成する」を参照してください。
WPF デザイナーで MainWindow.xaml が開きます。
Student という名前の新しいクラスをプロジェクトに追加します。 詳細については、「方法 : 新しいプロジェクト項目を追加する」を参照してください。
自動的に生成されたコードを次のコードで置き換えます。
Imports System Imports System.Collections.ObjectModel Imports System.Windows ' Student is a simple class that stores a name and an ' IsEnrolled value. Public Class Student ' The default constructor is required for creation from XAML. Public Sub New() End Sub ' The StudentName property is a string that holds the first and last name. Public Property StudentName As String ' The IsEnrolled property gets or sets a value indicating whether ' the student is currently enrolled. Public Property IsEnrolled As Boolean End Class ' The StudentList collection is declared for convenience, ' because declaring generic types in XAML is inconvenient. Public Class StudentList Inherits ObservableCollection(Of Student) End Class
using System; using System.Collections.ObjectModel; using System.Windows; namespace DataBindingDemo { // Student is a simple class that stores a name and an // IsEnrolled value. public class Student { // The default constructor is required for creation from XAML. public Student() { } // The StudentName property is a string that holds the first and last name. public string StudentName { get; set; } // The IsEnrolled property gets or sets a value indicating whether // the student is currently enrolled. public bool IsEnrolled { get; set; } } // The StudentList collection is declared for convenience, // because declaring generic types in XAML is inconvenient. public class StudentList : ObservableCollection<Student> { } }
BoolToBrushConverter という名前の新しいクラスをプロジェクトに追加します。
自動的に生成されたコードを次のコードで置き換えます。
Imports System Imports System.Globalization Imports System.Windows.Data Imports System.Windows.Media ' The BoolToBrushConverter class is a value converter ' that helps to bind a bool value to a brush property. <ValueConversion(GetType(Boolean), GetType(Brush))> _ Public Class BoolToBrushConverter Implements IValueConverter Public Function Convert( _ ByVal value As Object, _ ByVal targetType As Type, _ ByVal parameter As Object, _ ByVal culture As CultureInfo) As Object Implements IValueConverter.Convert Dim b As Brush = Nothing ' Only apply the conversion if value is assigned and ' is of type bool. If value IsNot Nothing AndAlso value.[GetType]() Is GetType(Boolean) Then ' true is painted with a green brush, ' false with a red brush. b = If(CBool(value), Brushes.Green, Brushes.Red) End If Return b End Function ' Not used. Public Function ConvertBack( _ ByVal value As Object, _ ByVal targetType As Type, _ ByVal parameter As Object, _ ByVal culture As CultureInfo) As Object Implements IValueConverter.ConvertBack Return Nothing End Function End Class
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Windows.Data; using System.Windows.Media; namespace DataBindingDemo { // The BoolToBrushConverter class is a value converter // that helps to bind a bool value to a brush property. [ValueConversion(typeof(bool), typeof(Brush))] public class BoolToBrushConverter : IValueConverter { public object Convert( object value, Type targetType, object parameter, CultureInfo culture) { Brush b = null; // Only apply the conversion if value is assigned and // is of type bool. if (value != null && value.GetType() == typeof(bool)) { // true is painted with a green brush, // false with a red brush. b = (bool)value ? Brushes.Green : Brushes.Red; } return b; } // Not used. public object ConvertBack( object value, Type targetType, object parameter, CultureInfo culture) { return null; } } }
プロジェクトをビルドします。
WPF デザイナーで MainWindow.xaml を開きます。
自動的に生成された XAML を次の XAML に置き換えます。
<Window x:Class="DataBindingDemo.MainWindow" xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:DataBindingDemo" Title="Databinding Demo" Height="300" Width="300"> <Window.Resources> <local:StudentList x:Key="studentCollection" > <local:Student StudentName="Syed Abbas" IsEnrolled="false" /> <local:Student StudentName="Lori Kane" IsEnrolled="true" /> <local:Student StudentName="Steve Masters" IsEnrolled="false" /> <local:Student StudentName="Tai Yee" IsEnrolled="true" /> <local:Student StudentName="Brenda Diaz" IsEnrolled="true" /> </local:StudentList> <local:BoolToBrushConverter x:Key="boolToBrushConverter" /> <DataTemplate x:Key="listBoxTemplate"> <StackPanel Orientation="Horizontal" > <Rectangle Fill="{Binding Path=IsEnrolled, Converter={StaticResource boolToBrushConverter}}" Height="10" Width="10" Margin="0,0,5,0" /> <TextBlock Text="{Binding Path=StudentName}" /> </StackPanel> </DataTemplate> </Window.Resources> <Grid></Grid> </Window>
データ バインディングの割り当て
Binding を使用して、ListBox コントロールに studentCollection を表示します。 WPF デザイナー により、コードや XAML を書き込まずにデータ バインディングを使用できるようになります。
ListBox をデータ ソースにバインドするには
[プロパティ] ウィンドウで、ItemsSource プロパティまでスクロールします。
左の列の端にある [プロパティ マーカー] () をクリックします。
メニューが表示されます。
ヒント
行を右クリックしてメニューを表示することもできます。
[データ バインドの適用] をクリックします。
データ バインディング ビルダーが表示されます。
左パネルにある [ソース] ペインで、[StaticResource] をクリックします。
中央のペインで、[Window.Resources] をクリックします。
右パネルで、[studentCollection] をクリックします。
ListBox コントロールには、項目が設定されます。
[プロパティ] ウィンドウで、DisplayMemberPath プロパティまでスクロールし、その値を StudentName に設定します。
ListBox コントロールに、studentCollection の各 Student インスタンスの StudentName プロパティが表示されます。
値コンバーターを使用したデータ バインディングの作成
DataTemplate を作成して、ListBox コントロールのデータの形式を設定します。 このプロジェクトでは、ブール型プロパティを色付けされた四角形として表示するために、DataTemplate で値コンバーターを使用します。
値コンバーターを使用してデータ バインディングを作成するには
[プロパティ] ウィンドウで、DisplayMemberPath プロパティを削除します。
ItemTemplate プロパティまでスクロールします。
[プロパティ マーカー] () をクリックします。
[リソースの適用] をクリックします。
リソース ピッカーが表示されます。
[ローカル] セクションで、[listBoxTemplate] をクリックします。
ListBox コントロールでは、学生の名前の横に、学生が登録されているかどうかを示す赤色または緑色の四角形が表示されます。
次の手順
- データ バインディング ビルダーを使用すると、データ バインディングのプロパティを設定できます。 詳細については、「方法: WPF デザイナーを使用してデータ バインディングのプロパティを設定する」を参照してください。