Export (0) Print
Expand All

How to bind data in XAML Designer

In XAML Designer, you can set data binding properties by using the artboard and the Properties window. The example in this topic shows how to bind data to a control. Specifically, the procedure shows how to create a simple shopping cart class that has a DependencyProperty named ItemCount, and then bind the ItemCount property to the Text property of a TextBlock control.

To create a class to use as a data source

  1. Create a C# or Visual Basic project in the Blank App template.

  2. Open MainPage.xaml.cs (or MainPage.xaml.vb) and add the following code. In C#, add the code in the projectName namespace (before the final closing parenthesis in the file). In Visual Basic, just add the new class.

    public class ShoppingCart : DependencyObject
    {
        public int ItemCount
        {
            get { return (int)GetValue(ItemCountProperty); }
            set { SetValue(ItemCountProperty, value); }
        }
    
        public static readonly DependencyProperty ItemCountProperty =
             DependencyProperty.Register("ItemCount", typeof(int),
             typeof(ShoppingCart), new PropertyMetadata(0));
    }
    
    

    This code sets a value of 0 as the default item count by using the PropertyMetadata object.

    TipTip

    In Visual Studio, you can add stub code for a dependency property by typing propdp inside the ShoppingCart class and then pressing the TAB key.

  3. Click Build > Build Solution.

To bind the ItemCount property to a TextBlock control

  1. Right-click MainPage.xaml and then click View Designer.

  2. In the Document Outline window, select the root Grid panel, which appears as [Grid] in the window.

  3. With the Grid selected, click the New button next to the DataContext property in the Properties window.

  4. In the Select Object dialog box, make sure that Show all assemblies is cleared, and then select ShoppingCart under the projectName namespace, and then click OK.

    The following illustration shows Select Object dialog box with ShoppingCart selected.

    Select Object dialog box
  5. In the Toolbox, double-click a TextBlock control to add it to the artboard.

  6. With the TextBlock control selected, click the property marker to the right of the Text property under Common in the Properties window. (The property marker looks like a small box.)

  7. Click Create Data Binding in the resulting menu.

  8. With a binding type of Data context, which is the default value in the Binding type list, select the ItemCount property in the Path box, and then click OK.

    The following illustration shows the Create Data Binding dialog box with the ItemCount property selected.

    Create Data Binding dialog box
  9. Press F5 to start the app.

    The TextBlock control should show the default value of 0 as text.

Show:
© 2014 Microsoft