Udostępnij za pośrednictwem


Walkthrough: Binding Silverlight Controls to Objects

In this walkthrough, you will create a Silverlight application that contains data-bound controls. The controls are bound to 2 related user-defined business objects.

This walkthrough illustrates the following tasks:

  • Creating a Silverlight application.

  • Creating 2 related custom objects to bind to the user interface.

  • Running the Data Source Configuration Wizard to connect to the custom object which populates the Data Sources window.

  • Creating a set of data-bound controls by dragging items from the Data Sources window to the Silverlight Designer.

    Note

    Your computer might show different names or locations for some of the Visual Studio user interface elements in the following instructions. The Visual Studio edition that you have and the settings that you use determine these elements. For more information, see Visual Studio Settings.

Prerequisites

You need the following components to complete this walkthrough:

  • Visual Studio 2010.

Prior knowledge of the following concepts is also helpful, but not required to complete the walkthrough:

  • Working with the Silverlight Designer. For more information, see Silverlight.

  • Silverlight data binding. For more information, see Data Binding.

  • Working with XAML. For more information, see XAML.

Creating the Silverlight Application

Start this walkthrough by creating a Silverlight application.

To create the Silverlight project

  1. On the File menu, create a new project.

  2. Under the Visual C# or Visual Basic node, click Silverlight and then click Silverlight Application.

  3. In the Name box, type SilverlightObjectBinding and then click OK.

  4. Leave the default settings in the New Silverlight Application dialog box and then click OK.

    The Silverlight application is created as a solution with 2 projects: a SilverlightObjectBinding project and a SilverlightObjectBinding.Web project that is used to host the SilverlightObjectBinding project.

Creating Custom Objects to Bind to

To expose data to an application, a data model must be defined. In this walkthrough, you create custom objects that represent customers and orders for the data model.

To create Customers objects

  1. In Solution Explorer, right-click SilverlightObjectBinding project, point to Add, and then click New Item.

  2. In the Add New Item dialog box, click the Class item.

  3. Change the name to Customer, and then click Add.

  4. In the Customer code file, replace the Customer class with the following code:

    ''' <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>
    {
    
    }
    

To create Orders objects

  1. In Solution Explorer, right-click SilverlightObjectBinding project, point to Add, and then click New Item.

  2. In the Add New Item dialog box, click the Class item.

  3. Change the name to Order, and then click Add.

  4. In the Order code file, replace the Order class with the following code:

    ''' <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. Build the project.

Creating the Object Data Source

Create an object data source and populate the Data Sources window by running the Data Source Configuration Wizard.

To create the object data source

  1. On the Data menu, click Show Data Sources.

  2. In the Data Sources window, click Add New Data Source.

    The Data Source Configuration Wizard appears.

  3. In the Choose a Data Source Type page, click Object and then click Next.

  4. In the Select the Data Objects page, expand the tree view twice, and then select the check box next to Customers.

    Note

    Be sure to select Customers, and not the singular Customer. If Customers is not available, exit the wizard and rebuild the solution.

  5. Click Finish.

    The Data Sources window is populated with the object data source.

Creating the Data-bound Controls

Create controls that display data in the objects by dragging the Customers and Orders nodes from the Data Sources window to the designer.

To create the data-bound controls

  1. Open MainPage.xaml in design view.

  2. From the Data Sources window, drag the Customers node to the designer.

  3. From the Data Sources window, drag the Orders node to the designer below the customers grid.

Populate the Objects with Data and Bind Them to the Generated CollectionViewSource

Because this walkthrough uses custom objects as a data model, sample data is created and loaded when the Silverlight page opens.

After you drag an object data source from the Data Sources window, a code comment is generated to help configure the data source to point to your custom object. Uncomment the generated code comment and set System.Windows.Data.CollectionViewSource.Source (myCollectionViewSource) to point to your collection of data objects. The following procedure shows how to modify the generated code to bind it to the generated controls.

Every time that you drag items from the Data Sources window to the designer, a System.Windows.Data.CollectionViewSource is generated on the Silverlight page. Its name is based on the data source you are using. Replace the comment that reads: 'Resource Key for CollectionViewSource' with either CustomersViewSource or customerViewSource, depending on the language.

To populate the objects with data and bind the controls to the objects

  1. In Solution Explorer, expand the MainPage.xaml node, and then double-click the MainPage.xaml code file.

  2. In the code file (MainPage.xaml.vb or MainPage.xaml.cs) add the following method to the MainPage class:

    ' 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. Replace the commented code inside the UserControl_Loaded event handler with the following:

    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();
        }
    }
    

Testing the Application

Build and run the application to verify that you can view customer records.

To test the application

  1. On Build menu, click Build Solution. Verify that the solution builds without errors.

  2. Run the application.

  3. Verify the 3 Customers appear in the datagrid and the selected customer's orders are displayed in the orders grid.

  4. Select a different customer and verify the orders are updated to display only the orders of the selected customer.

  5. Close the application.

Next Steps

After completing this walkthrough, you can perform the following related tasks:

  • Learn how to save changes back to your data store. For more information, see Data Binding.

See Also

Other Resources

Accessing Data in Visual Studio

Data Access and Data Structures