チュートリアル: オブジェクトへの Silverlight コントロールのバインド

このチュートリアルでは、データ バインド コントロールを含む Silverlight アプリケーションを作成します。 コントロールは、2 つの関連するユーザー定義ビジネス オブジェクトにバインドします。

このチュートリアルでは、次の作業について説明します。

  • Silverlight アプリケーションを作成する。

  • ユーザー インターフェイスにバインドする 2 つの関連するカスタム オブジェクトを作成する。

  • データ ソース構成ウィザードを実行して [データ ソース] ウィンドウに読み込まれるカスタム オブジェクトに接続する。

  • [データ ソース] ウィンドウから Silverlight Designer に項目をドラッグして一連のデータ バインド コントロールを作成する。

    注意

    次の手順で参照している Visual Studio ユーザー インターフェイス要素の一部は、お使いのコンピューターでは名前や場所が異なる場合があります。 これらの要素は、使用する Visual Studio のエディションとその設定によって決まります。 詳細については、「設定の操作」を参照してください。

必須コンポーネント

このチュートリアルを実行するには、次のコンポーネントが必要です。

  • Visual Studio 2010.

次の概念に関する予備知識があると役に立ちますが、チュートリアルを完了するうえで必須ではありません。

  • Silverlight Designer の操作。 詳細については、「Silverlight」を参照してください。

  • Silverlight のデータ バインディング。 詳細については、「データ バインディング」を参照してください。

  • XAML の使用。 詳細については、「XAML (XAML)」を参照してください。

Silverlight アプリケーションの作成

このチュートリアルでは、最初に Silverlight アプリケーションを作成します。

Silverlight プロジェクトを作成するには

  1. [ファイル] メニューで、新しいプロジェクトを作成します。

  2. [Visual C#] ノードまたは [Visual Basic] ノードで、[Silverlight] をクリックし、[Silverlight アプリケーション] をクリックします。

  3. [名前] ボックスに「SilverlightObjectBinding」と入力し、[OK] をクリックします。

  4. [新しい Silverlight アプリケーション] ダイアログ ボックスで既定の設定を使用し、[OK] をクリックします。

    Silverlight アプリケーションが 2 つのプロジェクトを含むソリューションとして作成されます。プロジェクトの 1 つは、SilverlightObjectBinding プロジェクトです。もう 1 つは、SilverlightObjectBinding プロジェクトをホストするために使用される SilverlightObjectBinding Web プロジェクトです。

バインド先のカスタム オブジェクトの作成

アプリケーションにデータを公開するには、データ モデルを定義する必要があります。 このチュートリアルでは、顧客と注文を表すカスタム オブジェクトをデータ モデルとして作成します。

Customer オブジェクトを作成するには

  1. ソリューション エクスプローラー[SilverlightObjectBinding] プロジェクトを右クリックし、[追加] をポイントし、[新しい項目] をクリックします。

  2. [新しい項目の追加] ダイアログ ボックスで、[クラス] 項目をクリックします。

  3. 名前を「Customer」に変更し、[追加] をクリックします。

  4. Customer コード ファイルで、Customer クラスを次のコードで置き換えます。

    ''' <summary>
    ''' A single customer
    ''' </summary>
    Public Class Customer
    
        Public Sub New()
        End Sub
    
        ''' <summary>
        ''' Creates a new customer
        ''' </summary>
        ''' <param name="customerId">The ID that uniquely identifies this customer</param>
        ''' <param name="companyName">The name for this customer</param>
        ''' <param name="city">The city for this customer</param>
        Public Sub New(ByVal customerId As String,
                       ByVal companyName As String,
                       ByVal city As String)
            customerIDValue = customerId
            companyNameValue = companyName
            cityValue = city
        End Sub
    
        Private customerIDValue As String
        ''' <summary>
        ''' The ID that uniquely identifies this customer
        ''' </summary>
        Public Property CustomerID() As String
            Get
                Return customerIDValue
            End Get
            Set(ByVal value As String)
                customerIDValue = value
            End Set
        End Property
    
        Private companyNameValue As String
        ''' <summary>
        ''' The name for this customer
        ''' </summary>
        Public Property CompanyName() As String
            Get
                Return companyNameValue
            End Get
            Set(ByVal Value As String)
                companyNameValue = Value
            End Set
        End Property
    
        Private cityValue As String
        ''' <summary>
        ''' The city for this customer
        ''' </summary>
        Public Property City() As String
            Get
                Return cityValue
            End Get
            Set(ByVal Value As String)
                cityValue = Value
            End Set
        End Property
    
        Private ordersValue As Orders
        ''' <summary>
        ''' The orders for this customer
        ''' </summary>
        Public Property Orders As Orders
            Get
                Return ordersValue
            End Get
            Set(ByVal value As Orders)
                ordersValue = value
            End Set
        End Property
    
    
        Public Overrides Function ToString() As String
            Return Me.CompanyName & " (" & Me.CustomerID & ")"
        End Function
    End Class
    
    
    ''' <summary>
    ''' A collection of Customer objects.
    ''' </summary>
    ''' <remarks></remarks>
    Public Class Customers
        Inherits System.Collections.Generic.List(Of Customer)
    
    End Class
    
    /// <summary>
    /// A single customer
    /// </summary>
    public class Customer
    {
        /// <summary>
        /// Creates a new customer
        /// </summary>
        public Customer()
        {
        }
    
        /// <summary>
        /// Creates a new customer
        /// </summary>
        /// <param name="customerID"></param>
        /// <param name="companyName"></param>
        /// <param name="city"></param>
        public Customer(string customerID, string companyName,
           string city)
        {
            customerIDValue = customerID;
            companyNameValue = companyName;
            cityValue = city;
        }
    
        private string customerIDValue;
        /// <summary>
        /// The ID that uniquely identifies this customer
        /// </summary>
        public string CustomerID
        {
            get { return customerIDValue; }
            set { customerIDValue = value; }
        }
    
        private string companyNameValue;
        /// <summary>
        /// The name for this customer
        /// </summary>
        public string CompanyName
        {
            get { return companyNameValue; }
            set { companyNameValue = value; }
        }
    
        private string cityValue;
        /// <summary>
        /// The city for this customer
        /// </summary>
        public string City
        {
            get { return cityValue; }
            set { cityValue = value; }
        }
    
        private Orders ordersValue;
        /// <summary>
        /// The orders for this customer
        /// </summary>
        public Orders Orders
        {
            get { return ordersValue; }
            set { ordersValue = value; }
        }
    
        public override string ToString()
        {
            return this.CompanyName + " (" + this.CustomerID + ")";
        }
    }
    
    /// <summary>
    /// A collection of Customer objects
    /// </summary>
    public class Customers : System.Collections.Generic.List<Customer>
    {
    
    }
    

Order オブジェクトを作成するには

  1. ソリューション エクスプローラー[SilverlightObjectBinding] プロジェクトを右クリックし、[追加] をポイントし、[新しい項目] をクリックします。

  2. [新しい項目の追加] ダイアログ ボックスで、[クラス] 項目をクリックします。

  3. 名前を「Order」に変更し、[追加] をクリックします。

  4. Order コード ファイルで、Order クラスを次のコードで置き換えます。

    ''' <summary>
    ''' A single order
    ''' </summary>
    Public Class Order
    
        Public Sub New()
        End Sub
    
        ''' <summary>
        ''' Creates a new order
        ''' </summary>
        ''' <param name="orderid">The identifier for this order</param>
        ''' <param name="customerID">The customer who placed this order</param>
        Public Sub New(ByVal orderid As Integer,
                       ByVal customerID As String)
            orderIDValue = orderid
            customerIDValue = customerID
        End Sub
    
        Private orderIDValue As Integer
        ''' <summary>
        ''' Identifier for this order
        ''' </summary>
        Public Property OrderID() As Integer
            Get
                Return orderIDValue
            End Get
            Set(ByVal value As Integer)
                orderIDValue = value
            End Set
        End Property
    
        Private customerIDValue As String
        ''' <summary>
        ''' The customer who placed this order
        ''' </summary>
        Public Property CustomerID() As String
            Get
                Return customerIDValue
            End Get
            Set(ByVal Value As String)
                customerIDValue = Value
            End Set
        End Property
    End Class
    
    ''' <summary>
    ''' A collection of Orders
    ''' </summary>
    Public Class Orders
        Inherits System.Collections.Generic.List(Of Order)
    
    End Class
    
    /// <summary>
    /// A single order
    /// </summary>
    public class Order
    {
        /// <summary>
        /// Creates a new order
        /// </summary>
        /// <param name="orderid"></param>
        /// <param name="customerID"></param>
        public Order(int orderid, string customerID)
        {
            orderIDValue = orderid;
            customerIDValue = customerID;
        }
    
        private int orderIDValue;
        /// <summary>
        /// The ID that uniquely identifies this order
        /// </summary>
        public int OrderID
        {
            get { return orderIDValue; }
            set { orderIDValue = value; }
        }
    
        private string customerIDValue;
        /// <summary>
        /// The customer who placed this order
        /// </summary>
        public string CustomerID
        {
            get { return customerIDValue; }
            set { customerIDValue = value; }
        }
    }
    
    /// <summary>
    /// A collection of Order objects
    /// </summary>
    public class Orders : System.Collections.Generic.List<Order>
    {
    
    }
    
  5. プロジェクトをビルドします。

オブジェクト データ ソースの作成

データ ソース構成ウィザードを実行することにより、オブジェクト データ ソースを作成し、[データ ソース] ウィンドウに読み込みます。

オブジェクト データ ソースを作成するには

  1. [データ] メニューの [データ ソースの表示] をクリックします。

  2. [データ ソース] ウィンドウで、[新しいデータ ソースの追加] をクリックします。

    データ ソース構成ウィザードが表示されます。

  3. [データ ソースの種類を選択] ページで、[オブジェクト] をクリックし、[次へ] をクリックします。

  4. [データ オブジェクトの選択] ページで、ツリー ビューを 2 回展開し、[Customers] の横にあるチェック ボックスをオンにします。

    注意

    単数の [Customer] ではなく、[Customers] を選択してください。 [Customers] が表示されていない場合は、ウィザードを終了し、ソリューションをビルドし直します。

  5. [完了] をクリックします。

    [データ ソース] ウィンドウにオブジェクト データ ソースが読み込まれます。

データ バインド コントロールの作成

オブジェクトのデータを表示するコントロールを作成するには、[データ ソース] ウィンドウから [Customers] ノードおよび [Orders] ノードをデザイナーにドラッグします。

データ バインド コントロールを作成するには

  1. MainPage.xaml をデザイン ビューで開きます。

  2. [データ ソース] ウィンドウから、[Customers] ノードをデザイナーにドラッグします。

  3. [データ ソース] ウィンドウから、[Orders] ノードをデザイナーの顧客グリッドの下にドラッグします。

オブジェクトにデータを設定し、生成された CollectionViewSource にバインドする

このチュートリアルではカスタム オブジェクトをデータ モデルとして使用するため、Silverlight ページが開いたときにサンプル データを作成して読み込みます。

[データ ソース] ウィンドウからオブジェクト データ ソースをドラッグすると、コード コメントが生成され、カスタム オブジェクトを指すようにデータ ソースを構成できます。 生成されたコード コメントをコメントから外し、データ オブジェクトのコレクションを指すように [System.Windows.Data.CollectionViewSource.Source] (myCollectionViewSource) を設定します。 次の手順では、生成されたコードを変更して、生成されたコントロールにバインドする方法を示します。

[データ ソース] ウィンドウからデザイナーに項目をドラッグするたびに、Silverlight ページで [System.Windows.Data.CollectionViewSource] が生成されます。 名前は、使用しているデータ ソースに基づいて設定されます。 'Resource Key for CollectionViewSource' というコメントを、言語に応じて、CustomersViewSource または customerViewSource で置き換えます。

オブジェクトにデータを設定し、コントロールをオブジェクトにバインドするには

  1. ソリューション エクスプローラーで、[MainPage.xaml] ノードを展開し、[MainPage.xaml] コード ファイルをダブルクリックします。

  2. コード ファイル (MainPage.xaml.vb または MainPage.xaml.cs) で、次のメソッドを MainPage クラスに追加します。

    ' Create sample data.
    Private Function GetCustomers() As Customers
    
        Dim customers As New Customers
    
        ' Create 3 sample customers,
        ' each with 3 sample orders.
        Dim cust1 As New Customer("1", "A Bike Store", "Seattle")
        Dim cust1Orders As New Orders
        cust1Orders.Add(New Order(1, cust1.CustomerID))
        cust1Orders.Add(New Order(2, cust1.CustomerID))
        cust1Orders.Add(New Order(3, cust1.CustomerID))
        cust1.Orders = cust1Orders
    
        Dim cust2 As New Customer("2", "Progressive Sports", "Renton")
        Dim cust2Orders As New Orders
        cust2Orders.Add(New Order(4, cust2.CustomerID))
        cust2Orders.Add(New Order(5, cust2.CustomerID))
        cust2Orders.Add(New Order(6, cust2.CustomerID))
        cust2.Orders = cust2Orders
    
        Dim cust3 As New Customer("3", "Advanced Bike Components", "Irving")
        Dim cust3Orders As New Orders
        cust3Orders.Add(New Order(7, cust3.CustomerID))
        cust3Orders.Add(New Order(8, cust3.CustomerID))
        cust3Orders.Add(New Order(9, cust3.CustomerID))
        cust3.Orders = cust3Orders
    
        ' Add the sample customer objects to the 
        ' Customers collection.
        customers.Add(cust1)
        customers.Add(cust2)
        customers.Add(cust3)
    
        Return customers
    End Function
    
    // Create sample data.
    private Customers GetCustomers()
    {
        Customers customers = new Customers();
    
        // Create 3 sample customers,
        // each with 3 sample orders.
        Customer cust1 = new Customer("1", "A Bike Store", "Seattle");
        Orders cust1Orders = new Orders();
        cust1Orders.Add(new Order(1, cust1.CustomerID));
        cust1Orders.Add(new Order(2, cust1.CustomerID));
        cust1Orders.Add(new Order(3, cust1.CustomerID));
        cust1.Orders = cust1Orders;
    
        Customer cust2 = new Customer("2", "Progressive Sports", "Renton");
        Orders cust2Orders = new Orders();
        cust2Orders.Add(new Order(4, cust2.CustomerID));
        cust2Orders.Add(new Order(5, cust2.CustomerID));
        cust2Orders.Add(new Order(6, cust2.CustomerID));
        cust2.Orders = cust2Orders;
    
        Customer cust3 = new Customer("3", "Advanced Bike Components", "Irving");
        Orders cust3Orders = new Orders();
        cust3Orders.Add(new Order(7, cust3.CustomerID));
        cust3Orders.Add(new Order(8, cust3.CustomerID));
        cust3Orders.Add(new Order(9, cust3.CustomerID));
        cust3.Orders = cust3Orders;
    
        // Add the sample customer objects to the 
        // Customers collection.
        customers.Add(cust1);
        customers.Add(cust2);
        customers.Add(cust3);
    
        return customers;
    }
    
  3. UserControl_Loaded イベント ハンドラー内のコメントの付いたコードを次のコードで置き換えます。

    Private Sub UserControl_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
    
        'Do not load your data at design time.
        If Not (System.ComponentModel.DesignerProperties.GetIsInDesignMode(Me)) Then
            'Load your data here and assign the result to the CollectionViewSource.
            Dim myCollectionViewSource As System.Windows.Data.CollectionViewSource = CType(Me.Resources("CustomersViewSource"), System.Windows.Data.CollectionViewSource)
            myCollectionViewSource.Source = GetCustomers()
        End If
    End Sub
    
    private void UserControl_Loaded(object sender, RoutedEventArgs e)
    {
    
        // Do not load your data at design time.
        if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
        {
            //Load your data here and assign the result to the CollectionViewSource.
            System.Windows.Data.CollectionViewSource myCollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["customersViewSource"];
            myCollectionViewSource.Source = GetCustomers();
        }
    }
    

アプリケーションのテスト

アプリケーションをビルドして実行し、顧客レコードを表示できることを確認します。

アプリケーションをテストするには

  1. [ビルド] メニューの [ソリューションのビルド] をクリックします。 ソリューションがエラーなしでビルドされることを確認します。

  2. アプリケーションを実行します。

  3. 3 人の顧客がデータ グリッドに表示され、選択した顧客の注文が注文グリッドに表示されることを確認します。

  4. 別の顧客を選択し、選択した顧客の注文のみが表示されるように注文が更新されることを確認します。

  5. アプリケーションを閉じます。

次の手順

このチュートリアルを完了したら、関連する次の作業を行うことができます。

  • 変更をデータ ストアに保存する方法を学習します。 詳細については、「データ バインディング」を参照してください。

参照

その他の技術情報

Visual Studio でのデータへのアクセス

Data Access and Data Structures (データ アクセスとデータ構造)