Create WPF Master – Detail UI Using Data Sources Window Object DataSource

This article has a corresponding video that can be viewed here.

Master – Detail layouts are the bread and butter of Line of Business (LOB) applications. This walkthrough will show you how to drag & drop from the Data Sources Window to create the UI that is sourced from an Object DataSource.

This article has a C# and VB.NET download that includes both a completed solution and a starter solution. The starter solution includes the data entity classes and a static (Shared) data source class.

This walkthrough assumes that you’ll be starting with the starter solution.

Table of Contents

  1. Completed Application
  2. Starter Solution
  3. Adding a Title to the Form
  4. Adding the ComboBox Used for Record Selection
  5. Adding the Details Form
  6. Adding the DataGrid
  7. How does it Work?
  8. Comments

Completed Application 

Figure 1 Completed Application

Starter Solution 

Open the accompanying (C# or VB.NET) starter solution.

Figure 2 Starter Solution

The Data class provides two static (Shared) properties that expose an ObserveableCollection that the application will use as its data source. The Data class takes the place of a data layer that would be used to populate CLR classes from a database.

Figure 3 Data Class Diagram

The Customer class can contain one or more Addresses. Each Address has an associated AddressType.

Figure 4 Entity Class Diagram

Adding a Title to the Form 

Step One

Figure 5 Draw Border

  • Build the solution
  • Open ApplicationMainWindow.xaml
  • Select the root Grid by clicking inside the Window
  • Create a new Grid Row that takes up about 25% of the Window by
    • Click the Grid rail on the left to create a new row
  • Draw a Border control inside the new row
    • Select the Border control in the Toolbox then draw the Border as pictured in Figure 5 above

Step Two

  • Draw a TextBlock control inside the Border
  • Multi-select the TextBlock and Border controls using either the Document Outline or by CTRL + clicking each control
    • Right click, select Reset Layout, All
    • This will reset the Width, Height, HorizontalAlignment and VerticalAlignment properties to their default values

 ResetBorderTextBlockLayout

Figure 6 Reseting Values

  • After properties are reset your Window should look like Figure 7 below

Figure 7 Title Step Two

Step Three

  • Using the Document Outline, select the Border control
  • Using the Properties Window set the following properties:
    • CornerRadius to 30
    • Margin to 11
    • Padding to 7
    • BorderThickness to 2
    • Background to formTitleBackgroundBrush
      • Use Resource Picker, see Figure 8 below.  After opening Resource Picker, select formTitleBackgroundBrush.
    • BorderBrush to formTitleBorderBrush
      • Use Resource Picker, see Figure 8 below.  After opening Resource Picker, select formTitleBorderBrush.

    Figure 8 Applying Resource

  • Using the Document Outline, select the TextBlock
  • Using the Properties Window set the following properties
    • Text to Customer
    • VerticalAlignment to Center
    • FontSize to 18
    • FontWeight to Bold
    • Foreground to formTitleForegroundBrush
      • Use Resource Picker
  • Select the Grid
  • Hover cursor over the left Grid rail for the top row. Set top row to Auto sizing as in Figure 9 below
  • The bottom image in Figure 9 shows the completed form title

Figure 9 Auto Sizing Row

Adding the ComboBox Used for Record Selection 

Step One

  • Select the root Grid by clicking inside the Window
  • Create a new Grid Row that takes up about 25% of the Window
    • Click the Grid rail on the left to create a new row
  • Draw a StackPanel inside the new row
  • Add a TextBlock to the StackPanel by double clicking the TextBlock icon in the Toolbox
  • Add a ComboBox to the StackPanel by double clicking the ComboBox icon in the Toolbox
  • Form should now look like Figure 10 below

Figure 10 StackPanel

Step Two

  • Select the StackPanel
  • Right click on the StackPanel, choose Reset Layout, All
  • Using the Properties Window set the following properties:
    • Margin to 11
    • Orientation to Horizontal
  • Multi-select the TextBlock and ComboBox
  • Right click on the TextBlock and choose Reset Layout, All
  • Using the Properties Window set the following property:
    • VerticalAlignment to Center
  • Form should now look like Figure 11 below

    Figure 11 StackPanel

Step Three

  • Select the TextBlock
  • Using the Properties Window set the Text property to Select Customer
  • Select the ComboBox
  • Using the Properties Window set the following properties:
    • Margin to 7, 0
    • Width to 175
  • Form should now look like Figure 12 below

    Figure 12 Record Selector Completed

Step Four

From the Data menu, select Show Data Sources.

Figure 13 Data Menu

Figure 14 Data Sources Window

Important
Before clicking the Add New Data Source link, you must have built your solution.  The Data Sources Window uses reflection to discover types in your solution.  If the type has not been built yet, it will not appear in the Data Sources Window.
  • Add a new Data Source by clicking on the “Add New Data Source…” link pictured in Figure 14 above
  • When the Data Source Configuration Wizard is displayed select the Object icon and click the Next button

Figure 15 Select Data Objects

  • Drill down to the Customer object and select it, then press the Finish button
  • Figure 16 below shows the newly created Object Data Source

Figure 16 New Data Source

Step Five

The ComboBox will provide Customer selection. To wire up the ComboBox drag the Customer object and drop it on the ComboBox as pictured in Figure 17.

Figure 17 Binding ComboBox

  • Select the ComboBox
  • Using the Properties Window set the DisplayMemberPath to Name
  • Run application. You should be able to view data as pictured in Figure 18.

Figure 18 Run Application

Note
As part of the Solution Starter, the ApplicationMainWindow Loaded event has code that populates the CollectionViewSource for the application. This is code that developers would normally have to write as the Object Source drag and drop from the Data Sources Window does not add code to your projects.

Adding the Details Form 

The details form in this application plays the role of the Master in our Master-Details application.

Step One

Customize the Customer object output.

Figure 19 Change Layout Type

  • Change the Customer object layout to Details as pictured in Figure 19 above

Figure 20 Change CustomerID Control

  • Change the CustomerID field to use the Label control when rendered as pictured in Figure 20 above

Step Two

Figure 21 Adding New Row

  • Select the Grid and add a new row as pictured in Figure 21 above.

Figure 22 Details Form Generation

  • Drag and drop the Customer object to the Grid Row below the ComboBox
  • With the Details Grid selected, use the Properties Window and reset the following properties:
    • Height
    • Width
  • Using the Properties Window set the following properties:
    • VerticalAlignment to Top
    • Margin to 11
  • Select the outer Grid and change the Details Form row to use Auto sizing
  • The application should now look like Figure 23 below
  • Run the application and select different Customers

Figure 23 Details Form Completed

Adding the DataGrid 

Step One

Customize the Addresses object output.

  • Expand the Address node
  • Set the CustomerID field control to None

Step Two

Figure 24 Add Grid to Bottom Row

  • Add a Grid control to the bottom row
  • With Grid selected, right click, select Reset Layout, All
  • Using the Properties Window set the following property:
    • Margin to 11

Step Three

Figure 25 Drag and Drop DataGrid

  • Drag and drop the Addresses object from the Data Sources Window to the Grid control added in Step Two above
  • With DataGrid selected, right click, select Reset Layout, All
  • The DataGrid should now look like Figure 26 below

 

DataGridResized

Figure 26 Data Grid Resized

Step Four

Edit DataGrid columns using the XAML Editor.

Figure 27 DataGrid Columns

  • Insert a DataGridComboBoxColumn as pictured in Figure 27 above by copying the below XAML:

<DataGridComboBoxColumn SelectedValueBinding=”{Binding Path=AddressType.AddressTypeId, Mode=TwoWay}” ItemsSource=”{x:Static local:Data.AddressTypes}” DisplayMemberPath=”Name” Header=”Address Type” SelectedValuePath=”AddressTypeId” />

  • Cut and Paste the Street column so that it is above the City column as pictured in Figure 27 above.
  • Run you application
    • You can add, edit and delete rows in the DataGrid
    • Notice that the ComboBox in the DataGrid provides selection for the Address, AddressType.
Note
See How does it Work section below for an explanation of the DataGrid ComboBox.

How does it Work? 

The CollectionViewSource is a powerful class that provides a wrapper around a data source, adding sorting, grouping and filtering functionality without changing the source data.

The CollectionViewSource is a proxy class to the underlying CollectionView that provides navigation of collection items.

Information
MSDN CollectionViewSource documentation can be viewed here: http://msdn.microsoft.com/en-us/library/system.windows.data.collectionviewsource.aspx

Figure 28 Data Object Relationships

  • The Data.Customers ObservableCollection is the source for the CustomerViewSource. This data is wired up in the ApplicationMainWindow.Loaded event.
  • When the ComboBox selection changes it sets the CurrentItem on the underlying CollectionView.
  • The Details Form is bound to the CurrentItem. When selection changes, the Details Form DataContext changes and the selected Customer is displayed.
  • The CustomerAddressesViewSource is bound to the CurrentItem (current Customer) Addresses property.
  • The DataGrid is bound to the CustomerAddressesViewSource and displays all items in this collection.

DataGrid ComboBox

The DataGrid ComboBox displays the AddressType.Name for the Address and provides selection of an AddressType.

Figure 29 DataGrid ComboBox

  • SelectedValueBinding property gets and sets the AddressTypeId for the Address in the row
  • ItemsSource is set to the static (Shared) property AddressTypes exposed by the Data class. AddressTypes is a collection of AddressType.
  • DisplayMemberPath is the Name property of the AddressType
  • Header is the column header displayed in the DataGrid
  • SelectedValuePath is the AddressTypeId of the AddressType
Information
MSDN DataGridComboBoxColumn documentation can be viewed here:http://msdn.microsoft.com/en-us/library/system.windows.controls.datagridcomboboxcolumn(VS.100).aspx

Comments 

Microsoft values your opinion about our products and documentation. In addition to your general feedback it is very helpful to understand:

  • How the above feature enables your workflow
  • What is missing from the above feature that would be helpful to you

Thank you for your feedback and have a great day,

Autor: Karl Shifflett

Fonte: http://blogs.msdn.com/b/wpfsldesigner/archive/2010/01/19/create-wpf-master-detail-ui-using-data-sources-window-object-datasource.aspx
Visual Studio Cider Team

Anúncios

Sample Data in the WPF and Silverlight Designer

Objective

Requirements

Retail release of Visual Studio 2010 and the latest Silverlight 4 tools for Visual Studio 2010.

Table of Contents

  1. Background
  2. Faux Types and Real Types
  3. Images in Sample Data Files
  4. Adding New Sample Data File
  5. Consuming Sample Data File
  6. WPF Sample Data Scenarios
  7. Silverlight Sample Data Scenarios
  8. WCF RIA Services Sample Data Scenario
  9. Choosing Sample Data Loading Technique
  10. Comments

Background 

Cider and Blend 4

Developers using a visual Designer use sample data to light up their UI at design-time; to cause the Designer to render like it will at run-time. This time saving feature is especially important when designing DataTemplates or adjusting the layout of a DataGrid since the developer will not have to actually run the application to see what it will render like with data.

Sample data in Cider and Blend is easy to understand and wire up.

Sample data files are XAML files. Each sample data file contains one or more instances of user type’s instantiated in XAML. The XAML sample data file and resulting instances of data are connected to the UI using the d:DesignData MarkupExtension. d:DesignData can be applied to a data source declared in XAML like a CollectionViewSource, DomainDataSource or can be assigned to a d:DataContext property.

Each sample data file has an associated Build Action that determines if d:DesignData will create actual instances of the types in the sample data file or if faux types will be created. Faux types are necessary when the types in the sample data file are not creatable or if read-only properties need to be populated with sample data values.

Blend 4

Blend has tooling to create and modify XAML sample data for a class. Blend also provides a sample data drag and drop experience to wire up the d:DataContext and appropriate properties.

Blend provides an additional feature that enables creating XML sample data on the fly without a predefined class. The XML sample data can then be easily be configured and modified. This XML sample data only works in Blend.

To learn more about Blend please see the Expression Blend Blog, Unni’s Blog, Kirupa’s Blog or Christian Schormann’s Blog.

Faux Types and Real Types 

The term faux type is used in this document to indicate that a cloned type will be created instead of your actual type. Benefits of faux types include the ability to create an otherwise non-creatable type in sample data, the ability to set read-only properties in sample data and the by-passing of code in the real type’s constructor.

When using real types in sample data, be aware that any code in the type’s constructor will be executed at design-time. For an entity object this would not normally be an issue, but if the real type is a ViewModel, the code in that ViewModel’s constructor will be executed. If that constructor’s code loads data from a database for example, problems could occur in the Designer when the sample data is loaded. User code running at design-time is responsible for over 20% of all Designer load failures. You can read up on running code in a constructor in this blog post.

Images in Sample Data Files 

WPF Sample Data Files Only

If the image is part of the project, it can be referenced using the below relative folder syntax.

<m:Customer FirstName="Alfons" LastName="Parovszky" Photo="../Images/image01.png">

WPF and Silverlight Sample Data Files

All images in Silverlight sample data files require the pack syntax. WPF projects must use this syntax if the image is located in another assembly:

<m:Customer FirstName="Alfons" LastName="Parovszky" 
            Photo="/SLSampleDataScenarios;component/Images/image01.png">

 

If the image is not part of any project, you can use the below file:/// URI syntax to use an image in a sample data file.

<m:Customer FirstName="Alfons" LastName="Parovszky" 
            Photo="file:///c:/Images/markbou.jpg">

Adding New Sample Data File 

The following applies to both WPF and Silverlight applications.

  • Add a new ResourceDictionary or Text File to the project.
    • If ResourceDictionary delete the default file content.
    • If Text File, change file extension to .xaml
  • Using the file properties, set build action to either:
    • DesignData – will create faux types
    • DesignDataWithDesignTimeCreatableTypes – will create actual types
  • Using the file properties, set Copy to Output Directory to: Do not copy
  • Using the file properties, set Custom Tool:  <blank>
  • Using XAML Editor add your sample data content to the file.

Sample Data File Properties

Single Instance Sample Data Example

<m:Customer 
    xmlns:m="clr-namespace:SampleDataScenarios.Model" 
    FirstName="Alfons" LastName="Parovszky" 
    Photo="../Images/image01.png">
</m:Customer>

Multiple Instance Sample Data Example

<m:Customers xmlns:m="clr-namespace:SampleDataScenarios.Model">
    <m:Customer FirstName="Alfons" LastName="Parovszky" Photo="../Images/image01.png">
        <m:Customer.Addresses>
            <m:Address LineOne="125 North St" City="Greatville" State="CA" Zip="98004" />
            <m:Address LineOne="3000 1st St NE" City="Coolville" State="CA" Zip="98004" />
        </m:Customer.Addresses>
    </m:Customer>
    <m:Customer FirstName="Lori" LastName="Penor" Photo="../Images/image02.png">
        <m:Customer.Addresses>
            <m:Address LineOne="126 East St" City="Greatville" State="CA" Zip="98004" />
            <m:Address LineOne="3001 2st St NE" City="Coolville" State="CA" Zip="98004" />
        </m:Customer.Addresses>
    </m:Customer>
    <m:Customer FirstName="Justin" LastName="Harrison" Photo="../Images/image03.png">
        <m:Customer.Addresses>
            <m:Address LineOne="127 West St" City="Greatville" State="CA" Zip="98004" />
            <m:Address LineOne="3002 3st St NE" City="Coolville" State="CA" Zip="98004" />
        </m:Customer.Addresses>
    </m:Customer>
</m:Customers>

WPF Supported Sample Data File Scenarios

For sample data files where the root object is a single instance, simply add the type to the sample data file as done in Single Instance Sample Data Example above.

For collections, the root object can be an ArrayList or a custom type that derives from a collection or generic collection as done in Multiple Instance Sample Data Example above. Notice that WPF can also use the same technique as outlined below in Silverlight Scenarios. The Multiple Instance Sample Data Example uses the below DesignSampleDataCollection class as the root instead of an ArrayList.

Silverlight Supported Sample Data File Scenarios

For sample data files where the root object is a single instance, simply add the type to the sample data file as done in Single Instance Sample Data Example above.

For collections, the root object must be a type that derives from a collection or generic collection.

Non-WCF RIA Services Scenario

If the project does not have a collection object for the desired root type and the type does not derive from the RIA Services Entity object, you need to create a generic reusable collection like the below DesignSampleDataCollection.

C#

namespace SampleDataScenarios.Model {
  public class DesignTimeSampleDataCollection : List<Object> {

    public DesignTimeSampleDataCollection() { }
  }
}

VB.NET

Public Class DesignTimeSampleDataCollection
  Inherits List(Of Object)

  Public Sub New()

  End Sub

End Class

WCF RIA Services Scenario

If the project does not have a collection object for the desired root type and the type derives from the RIA Services Entity object, you need to create a generic reusable collection like the below DesignRIAEntitySampleDataCollection.

namespace ContosoSales.SampleData {
    public class DesignRIAEntitySampleDataCollection : 
          List<System.ServiceModel.DomainServices.Client.Entity> {

        public DesignRIAEntitySampleDataCollection() { }
    }
}

Consuming Sample Data File 

The d:DesignData Markup Extension assumes the role of a sample data file loader and parser that provides instantiated or faux types to the consumer.

Sample Data Consumers

The following design-time properties can consume the sample data provided by d:DesignData:

  • d:DataContext can be set on any FrameworkElement
  • d:DesignSource can be set on a CollectionViewSource
  • d:DesignData can be set on a DomainDataContext (RIA Services data object)

WPF Sample Data Scenarios 

Open either solution: CS-SampleDataScenarios or VB-SampleDataScenarios.

Rebuild solution.

The WPF samples are in the SampleDataScenarios project.

Demo-01 Single Customer

Open Demo01SingleCustomer.xaml.

This is an example of a single instance sample data file consumed by a form. The single instance of Customer has 2 instances of Address.

<m:Customer 
    xmlns:m="clr-namespace:SampleDataScenarios.Model" 
    FirstName="Alfons" LastName="Parovszky" 
    Photo="../Images/image01.png">
    <m:Customer.Addresses>
        <m:Address LineOne="125 North St" City="Greatville" State="CA" Zip="98004" />
        <m:Address LineOne="3000 1st St NE" City="Coolville" State="CA" Zip="98004" />
    </m:Customer.Addresses>
</m:Customer>

In the below form, the Customer type is available in the root Grid’s DataContext. This is important because the presence of d:DesignData and sample data not only feeds the DataContext to render data, but also enables the Designer tooling for creating and editing bindings using the Binding Builder.

Connecting Sample Data

In the below XAML the CustomerSampleData.xaml file is loaded and parsed by the d:DesignData Markup Extension and assigned to the d:DataContext for the Grid. Child controls of the Grid can data bind to properties on the DataContext and the Designer Binding Builder tooling is enabled.

<Grid d:DataContext="{d:DesignData Source=/SampleData/CustomerSampleData.xaml}">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>

    <TextBlock Text="Demo-01 Single Customer" Grid.ColumnSpan="2" FontWeight="Bold" FontSize="14" Margin="11" />

    <Grid Grid.Row="1" Margin="6">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>

        <TextBlock Text="First Name:" VerticalAlignment="Center" Width="75" />
        <TextBox Text="{Binding Path=FirstName}" VerticalAlignment="Center" Grid.Column="1"/>

        <TextBlock Text="Last Name:" VerticalAlignment="Center" Width="75" Grid.Row="1" />
        <TextBox Text="{Binding Path=LastName}" VerticalAlignment="Center" Grid.Row="1" Grid.Column="1" />

        <TextBlock Text="Ranking:" VerticalAlignment="Center" Width="75" Grid.Row="2" />
        <TextBlock Text="{Binding Path=Ranking}" VerticalAlignment="Center"  Grid.Row="2" Grid.Column="1" />

        <TextBlock Margin="7" Text="Addresses" FontWeight="Bold" Grid.Row="3" Grid.ColumnSpan="2" />

        <ListBox ItemsSource="{Binding Path=Addresses}" Grid.Row="4" Grid.ColumnSpan="2">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="100" />
                            <ColumnDefinition Width="75" />
                            <ColumnDefinition Width="30" />
                            <ColumnDefinition Width="Auto" />
                        </Grid.ColumnDefinitions>
                        <TextBlock Text="{Binding Path=LineOne}" />
                        <TextBlock Text="{Binding Path=City}" Grid.Column="1" />
                        <TextBlock Text="{Binding Path=State}" Grid.Column="2" />
                        <TextBlock Text="{Binding Path=Zip}" Grid.Column="3" />
                    </Grid>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

    </Grid>

    <Image VerticalAlignment="Top" Source="{Binding Path=Photo}" Grid.Row="1" Grid.Column="1" Margin="6" />
</Grid>

Demo-02 Single Not Creatable Customer

Open Demo02SingleNotCreatableCustomer.xaml and NotCreatableCustomer.cs.

This is an example of a single instance sample data file where the entity object is not creatable. The NotCreatableCustomer class has a private constructor. The single instance of NotCreatableCustomer has 2 instances of Address.

Non-creatable types are common scenario in .NET, making this feature a very important addition to the Designer tooling. For example, RIA Services Entity types or types that are created by factories cannot be instantiated. Without this feature sample data would not work and the Designer tooling would be unable to provide DataContext and property name lists for a type.

Important
Sample data files that contain non-creatable types must have their Build Action set to: DesignData and not DesignDataWithDesignTimeCreatableTypes.
<m:Customer 
    xmlns:m="clr-namespace:SampleDataScenarios.Model" 
    FirstName="Alfons" LastName="Parovszky" 
    Photo="../Images/image01.png" Ranking="101">
    <m:Customer.Addresses>
        <m:Address LineOne="125 North St" City="Greatville" State="CA" Zip="98004" />
        <m:Address LineOne="3000 1st St NE" City="Coolville" State="CA" Zip="98004" />
    </m:Customer.Addresses>
</m:Customer>

In the below form, the NotCreatableCustomer type is available in the root Grid’s DataContext. Again, even though the NotCreatableCustomer type has a private constructor the sample data displays and the Binding Builder works normally.

Connecting Sample Data

In the below XAML the NotCreatableCustomerSampleData.xaml file is loaded and parsed by the d:DesignData Markup Extension and assigned to the d:DataContext for the Grid. Child controls of the Grid can data bind to properties on the DataContext and the Designer Binding Builder tooling is enabled.

<Grid d:DataContext="{d:DesignData Source=/SampleData/NotCreatableCustomerSampleData.xaml}">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>

    <TextBlock Text="Demo-02 Single Not Creatable Customer" Grid.ColumnSpan="2" FontWeight="Bold" FontSize="14" Margin="11" />

    <Grid Grid.Row="1" Margin="6">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>

        <TextBlock Text="First Name:" VerticalAlignment="Center" Width="75" />
        <TextBox Text="{Binding Path=FirstName}" VerticalAlignment="Center" Grid.Column="1"/>

        <TextBlock Text="Last Name:" VerticalAlignment="Center" Width="75" Grid.Row="1" />
        <TextBox Text="{Binding Path=LastName}" VerticalAlignment="Center" Grid.Row="1" Grid.Column="1" />

        <TextBlock Text="Ranking:" VerticalAlignment="Center" Width="75" Grid.Row="2" />
        <TextBlock Text="{Binding Path=Ranking}" VerticalAlignment="Center"  Grid.Row="2" Grid.Column="1" />

        <TextBlock Margin="7" Text="Addresses" FontWeight="Bold" Grid.Row="3" Grid.ColumnSpan="2" />

        <ListBox ItemsSource="{Binding Path=Addresses}" Grid.Row="4" Grid.ColumnSpan="2">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="100" />
                            <ColumnDefinition Width="75" />
                            <ColumnDefinition Width="30" />
                            <ColumnDefinition Width="Auto" />
                        </Grid.ColumnDefinitions>
                        <TextBlock Text="{Binding Path=LineOne}" />
                        <TextBlock Text="{Binding Path=City}" Grid.Column="1" />
                        <TextBlock Text="{Binding Path=State}" Grid.Column="2" />
                        <TextBlock Text="{Binding Path=Zip}" Grid.Column="3" />
                    </Grid>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

    </Grid>

    <Image VerticalAlignment="Top" Source="{Binding Path=Photo}" Grid.Row="1" Grid.Column="1" Margin="3" />
</Grid>

Demo-03 Customer ViewModel

Open Demo03CustomerViewModel.xaml.

This is an example of using a design-time ViewModel as the d:DataContext. DesignTimeCustomerViewModel derives from CustomerViewModel. In its constructor it populates the ViewModel properties and collection. Since the DesignTimeCustomerViewModel’s properties are populated, they are rendered on the design surface.

The below code demonstrates creating sample data instead of using the typical sample data XAML file.

C#

namespace SampleDataScenarios.ViewModel {
  public class DesignTimeCustomerViewModel : CustomerViewModel {

    public DesignTimeCustomerViewModel()
      : base() {

      base.Customer = new Customer() {
        FirstName = "Alfons", LastName = "Parovszky", Photo = "../Images/image01.png"
      };
      base.Customer.CalculateRank();
      base.Customer.Addresses.Add(
          new Address() { LineOne = "125 North St", City = "Greatville", State = "CA", Zip = "98004" });
      base.Customer.Addresses.Add(
          new Address() { LineOne = "3000 1st St NE", City = "Coolville", State = "CA", Zip = "98004" });
    }
  }
}

VB.NET

Public Class DesignTimeCustomerViewModel
  Inherits CustomerViewModel

  Public Sub New()
    MyBase.New()

    MyBase.Customer = New Customer With {.FirstName = "Alfons", .LastName = "Parovszky", .Photo = "../Images/image01.png"}
    MyBase.Customer.CalculateRank()
    MyBase.Customer.Addresses.Add(New Address With {.LineOne = "125 North St", .City = "Greatville", .State = "CA", .Zip = "98004"})
    MyBase.Customer.Addresses.Add(New Address With {.LineOne = "3000 1st St NE", .City = "Coolville", .State = "CA", .Zip = "98004"})

  End Sub

End Class

Connecting Sample Data

The below XAML demonstrates using d:DesignInstance with IsDesignTimeCreatable set to true to have Visual Studio instantiate DesignTimeCustomerViewModel and assign the instance as the d:DataContext. Since the instantiated instance has properties populated with data, that data will render exactly like other XAML file sample data in the Designer. This works because the DesignTimeCustomerViewModel is creatable at design-time and the below DesignInstance has IsDesignTimeCreatable set to true. Child controls of the Grid can data bind to properties on the DataContext and the Designer Binding Builder tooling is enabled.

<Grid d:DataContext="{d:DesignInstance vm:DesignTimeCustomerViewModel, IsDesignTimeCreatable=True}">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>

    <TextBlock Text="{Binding Path=FormTitle}" Grid.ColumnSpan="2" FontWeight="Bold" FontSize="14" Margin="11" />

    <Grid Grid.Row="1" Margin="6" DataContext="{Binding Path=Customer}">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>

        <TextBlock Text="First Name:" VerticalAlignment="Center" Width="75" />
        <TextBox Text="{Binding Path=FirstName}" VerticalAlignment="Center" Grid.Column="1"/>

        <TextBlock Text="Last Name:" VerticalAlignment="Center" Width="75" Grid.Row="1" />
        <TextBox Text="{Binding Path=LastName}" VerticalAlignment="Center" Grid.Row="1" Grid.Column="1" />

        <TextBlock Text="Ranking:" VerticalAlignment="Center" Width="75" Grid.Row="2" />
        <TextBlock Text="{Binding Path=Ranking}" VerticalAlignment="Center"  Grid.Row="2" Grid.Column="1" />

        <TextBlock Margin="7" Text="Addresses" FontWeight="Bold" Grid.Row="3" Grid.ColumnSpan="2" />

        <ListBox ItemsSource="{Binding Path=Addresses}" Grid.Row="4" Grid.ColumnSpan="2">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="100" />
                            <ColumnDefinition Width="75" />
                            <ColumnDefinition Width="30" />
                            <ColumnDefinition Width="Auto" />
                        </Grid.ColumnDefinitions>
                        <TextBlock Text="{Binding Path=LineOne}" />
                        <TextBlock Text="{Binding Path=City}" Grid.Column="1" />
                        <TextBlock Text="{Binding Path=State}" Grid.Column="2" />
                        <TextBlock Text="{Binding Path=Zip}" Grid.Column="3" />
                    </Grid>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

    </Grid>

    <Image VerticalAlignment="Top" Source="{Binding Path=Customer.Photo}" Grid.Row="1" Grid.Column="1" Margin="6" />
</Grid>

Demo-04 Northwind Master Details Details

Open Demo04NorthwindMasterDetailsDetails.xaml.

This is an example of using chained CollectionViewSources where the top level CollectionViewSource is the DataContext for a form. It is assumed that the CollectionViewSources will be populated at run-time from a code-behind method.

This example uses an EntityFramework model for the entity types.

The below sample data file has 2 instances of Customer each with 1 instance of Order and each Order has three instances of Order_Detail.

<sysCol:ArrayList xmlns:sysCol="clr-namespace:System.Collections;assembly=mscorlib"
                  xmlns:nw="clr-namespace:SampleDataScenarios.NorthwindModel">
    <nw:Customer Contact_Name="Jim Hance" Company_Name="Adatum" Contact_Title="Software Developer" Customer_ID="1">
        <nw:Customer.Orders>
            <nw:Order Order_Date="12/12/2009" Ship_Name="Jim Hance" Customer_ID="1" Order_ID="1"
                      Ship_Address="125 North St" Employee_ID="74">
                <nw:Order.Order_Details>
                    <nw:Order_Detail Product_ID="125" Discount="50" Order_ID="1" Quantity="5" 
                                     Unit_Price="75.99" />
                    <nw:Order_Detail Product_ID="742" Order_ID="1" Quantity="9" Unit_Price="5.99" />
                    <nw:Order_Detail Product_ID="2555" Order_ID="1" Quantity="50" Unit_Price="6.25" />
                </nw:Order.Order_Details>
            </nw:Order>
        </nw:Customer.Orders>
    </nw:Customer>
    <nw:Customer Contact_Name="Michael Patten" Company_Name="Contoso" Contact_Title="Sales Manager" Customer_ID="2">
        <nw:Customer.Orders>
            <nw:Order Order_Date="12/12/2009" Ship_Name="Michael Patten" Customer_ID="2" Order_ID="71"
                      Ship_Address="125 North St" Employee_ID="55">
                <nw:Order.Order_Details>
                    <nw:Order_Detail Product_ID="547" Discount="50" Order_ID="71" Quantity="5" 
                                     Unit_Price="75.99" />
                    <nw:Order_Detail Product_ID="62" Order_ID="71" Quantity="9" Unit_Price="5.99" />
                    <nw:Order_Detail Product_ID="11" Order_ID="71" Quantity="50" Unit_Price="6.25" />
                </nw:Order.Order_Details>
            </nw:Order>
        </nw:Customer.Orders>
    </nw:Customer>
</sysCol:ArrayList>

Connecting Sample Data

In the below XAML the NorthwindSampleData.xaml file is loaded and parsed by the d:DesignData Markup Extension and assigned to the d:DesignSource for the top level customersViewSource CollectionViewSource. The two remaining CollectionViewSources chain to collection properties on the customersViewSource.

Child controls of the Grid can data bind to properties on the DataContext and the Designer Binding Builder tooling is enabled. Notice the two DataGrid ItemsSource’s are the two chained CollectionViewSources. The two DataGrid’s also have their sample data populated and the Designer Binding Builder tooling is enabled.

<UserControl.Resources>
  <CollectionViewSource 
    x:Key="customersViewSource" 
    d:DesignSource="{d:DesignData Source=../SampleData/NorthwindSampleData.xaml}" />
  <CollectionViewSource 
    x:Key="customersOrdersViewSource" 
    Source="{Binding Path=Orders, Source={StaticResource customersViewSource}}" />
  <CollectionViewSource 
    x:Key="customersOrdersOrder_DetailsViewSource" 
    Source="{Binding Path=Order_Details, Source={StaticResource customersOrdersViewSource}}" />
</UserControl.Resources>
<Grid DataContext="{StaticResource customersViewSource}">
  <Grid.RowDefinitions>
    <RowDefinition Height="Auto" />
    <RowDefinition Height="*" />
    <RowDefinition Height="*" />
  </Grid.RowDefinitions>
  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="200" />
    <ColumnDefinition Width="*" />
  </Grid.ColumnDefinitions>

  <TextBlock Text="Demo-04 Northwind Master Details Details" Grid.ColumnSpan="2" FontWeight="Bold" FontSize="14" Margin="11" />

  <ListView 
    SelectedIndex="0" ItemsSource="{Binding}" Name="customersListView" SelectionMode="Single" 
    Margin="3.5,4" Grid.RowSpan="2" Grid.Row="1">
    <ListView.ItemContainerStyle>
      <Style>
        <Setter Property="Control.HorizontalContentAlignment" Value="Stretch" />
        <Setter Property="Control.VerticalContentAlignment" Value="Stretch" />
      </Style>
    </ListView.ItemContainerStyle>
    <ListView.View>
      <GridView>
        <GridViewColumn x:Name="company_NameColumn" Header="Company Name" Width="90">
          <GridViewColumn.CellTemplate>
            <DataTemplate>
              <TextBox 
                Margin="-6,-1" 
                Text="{Binding Path=Company_Name, Mode=TwoWay, ValidatesOnExceptions=true, NotifyOnValidationError=true}" />
            </DataTemplate>
          </GridViewColumn.CellTemplate>
        </GridViewColumn>
        <GridViewColumn x:Name="contact_NameColumn" Header="Contact Name" Width="90">
          <GridViewColumn.CellTemplate>
            <DataTemplate>
              <TextBox 
                Margin="-6,-1" 
                Text="{Binding Path=Contact_Name, Mode=TwoWay, ValidatesOnExceptions=true, NotifyOnValidationError=true}" />
            </DataTemplate>
          </GridViewColumn.CellTemplate>
        </GridViewColumn>
      </GridView>
    </ListView.View>
  </ListView>

  <Grid Grid.Column="1" Margin="3.5" Grid.Row="1">
    <DataGrid 
      AutoGenerateColumns="False" EnableRowVirtualization="True" 
      ItemsSource="{Binding Source={StaticResource customersOrdersViewSource}}" 
      Name="ordersDataGrid" RowDetailsVisibilityMode="VisibleWhenSelected" Margin="3.5">
      <DataGrid.Columns>
        <DataGridTextColumn 
          x:Name="order_IDColumn" Binding="{Binding Path=Order_ID}" Header="Order ID" Width="SizeToHeader" />
        <DataGridTextColumn 
          x:Name="customer_IDColumn" Binding="{Binding Path=Customer_ID}" 
          Header="Customer ID" Width="SizeToHeader" />
        <DataGridTextColumn 
          x:Name="employee_IDColumn" Binding="{Binding Path=Employee_ID}" 
          Header="Employee ID" Width="SizeToHeader" />
        <DataGridTextColumn 
          x:Name="ship_NameColumn" Binding="{Binding Path=Ship_Name}" 
          Header="Ship Name" Width="SizeToHeader" />
        <DataGridTextColumn 
          x:Name="ship_AddressColumn" Binding="{Binding Path=Ship_Address}" 
          Header="Ship Address" Width="SizeToHeader" />
        <DataGridTextColumn 
          x:Name="ship_CityColumn" Binding="{Binding Path=Ship_City}" 
          Header="Ship City" Width="SizeToHeader" />
        <DataGridTextColumn 
          x:Name="ship_RegionColumn" Binding="{Binding Path=Ship_Region}" 
          Header="Ship Region" Width="SizeToHeader" />
        <DataGridTextColumn 
          x:Name="ship_Postal_CodeColumn" Binding="{Binding Path=Ship_Postal_Code}" 
          Header="Ship Postal Code" Width="SizeToHeader" />
        <DataGridTextColumn 
          x:Name="ship_CountryColumn" Binding="{Binding Path=Ship_Country}" 
          Header="Ship Country" Width="SizeToHeader" />
        <DataGridTextColumn 
          x:Name="ship_ViaColumn" Binding="{Binding Path=Ship_Via}" 
          Header="Ship Via" Width="SizeToHeader" />
        <DataGridTemplateColumn 
          x:Name="order_DateColumn" Header="Order Date" Width="SizeToHeader">
          <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
              <DatePicker 
                SelectedDate="{Binding Path=Order_Date, Mode=TwoWay, 
                                ValidatesOnExceptions=true, NotifyOnValidationError=true}" />
            </DataTemplate>
          </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
        <DataGridTemplateColumn x:Name="required_DateColumn" Header="Required Date" Width="SizeToHeader">
          <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
              <DatePicker 
                SelectedDate="{Binding Path=Required_Date, Mode=TwoWay, 
                                ValidatesOnExceptions=true, NotifyOnValidationError=true}" />
            </DataTemplate>
          </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
        <DataGridTemplateColumn x:Name="shipped_DateColumn" Header="Shipped Date" Width="SizeToHeader">
          <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
              <DatePicker 
                SelectedDate="{Binding Path=Shipped_Date, Mode=TwoWay, 
                                ValidatesOnExceptions=true, NotifyOnValidationError=true}" />
            </DataTemplate>
          </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
        <DataGridTextColumn 
          x:Name="freightColumn" Binding="{Binding Path=Freight}" 
          Header="Freight" Width="SizeToHeader" />
      </DataGrid.Columns>
    </DataGrid>
  </Grid>
  <DataGrid 
    AutoGenerateColumns="False" EnableRowVirtualization="True" Grid.Column="1" Grid.Row="2" 
    ItemsSource="{Binding Source={StaticResource customersOrdersOrder_DetailsViewSource}}" 
    Name="order_DetailsDataGrid" RowDetailsVisibilityMode="VisibleWhenSelected" Margin="3.5">
    <DataGrid.Columns>
      <DataGridTextColumn 
        x:Name="order_IDColumn1" Binding="{Binding Path=Order_ID}" 
        Header="Order ID" Width="SizeToHeader" />
      <DataGridTextColumn 
        x:Name="product_IDColumn" Binding="{Binding Path=Product_ID}" 
        Header="Product ID" Width="SizeToHeader" />
      <DataGridTextColumn 
        x:Name="unit_PriceColumn" Binding="{Binding Path=Unit_Price}" 
        Header="Unit Price" Width="SizeToHeader" />
      <DataGridTextColumn 
        x:Name="quantityColumn" Binding="{Binding Path=Quantity}" 
        Header="Quantity" Width="SizeToHeader" />
      <DataGridTextColumn 
        x:Name="discountColumn" Binding="{Binding Path=Discount}" 
        Header="Discount" Width="SizeToHeader" />
    </DataGrid.Columns>
  </DataGrid>
</Grid>

Demo-05 Select Customer From List

Open Demo05SelectCustomerFromList.xaml.

This is an example of a multiple instance sample data file consumed by a form. The sample data consists of 3 Customers, each with 2 Addresses.

<m:Customers xmlns:m="clr-namespace:SampleDataScenarios.Model">
    <m:Customer FirstName="Alfons" LastName="Parovszky" Photo="../Images/image01.png">
        <m:Customer.Addresses>
            <m:Address LineOne="125 North St" City="Greatville" State="CA" Zip="98004" />
            <m:Address LineOne="3000 1st St NE" City="Coolville" State="CA" Zip="98004" />
        </m:Customer.Addresses>
    </m:Customer>
    <m:Customer FirstName="Lori" LastName="Penor" Photo="../Images/image02.png">
        <m:Customer.Addresses>
            <m:Address LineOne="126 East St" City="Greatville" State="CA" Zip="98004" />
            <m:Address LineOne="3001 2st St NE" City="Coolville" State="CA" Zip="98004" />
        </m:Customer.Addresses>
    </m:Customer>
    <m:Customer FirstName="Justin" LastName="Harrison" Photo="../Images/image03.png">
        <m:Customer.Addresses>
            <m:Address LineOne="127 West St" City="Greatville" State="CA" Zip="98004" />
            <m:Address LineOne="3002 3st St NE" City="Coolville" State="CA" Zip="98004" />
        </m:Customer.Addresses>
    </m:Customer>
</m:Customers>

In the below form, the collection of Customers is available in the root Grid’s DataContext. This is important because the presence of d:DesignData and sample data not only feeds the DataContext to render data, but also enables the Designer tooling for creating and editing bindings in the Binding Builder.

The data entry form to the right of the ListBox, has its DataContext set to the ListBox.SelectedItem. When ListBox selection changes the form data automatically changes.

Connecting Sample Data

In the below XAML the CustomersSampleData.xaml file is loaded and parsed by the d:DesignData Markup Extension and assigned to the d:DataContext for the Grid. Child controls of the Grid can data bind to properties on the DataContext and the Designer Binding Builder tooling is enabled.

<Grid d:DataContext="{d:DesignData Source=/SampleData/CustomersSampleData.xaml}">
  <Grid.RowDefinitions>
    <RowDefinition Height="Auto" />
    <RowDefinition Height="*" />
  </Grid.RowDefinitions>
  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="126" />
    <ColumnDefinition Width="*" />
    <ColumnDefinition Width="*" />
  </Grid.ColumnDefinitions>

  <TextBlock Text="Demo-05 Select Customer From List" Grid.ColumnSpan="3" 
                  FontWeight="Bold" FontSize="14" Margin="11" />

  <ListBox SelectedIndex="0" x:Name="lbCustomers" Grid.Row="1" Margin="6" ItemsSource="{Binding}">
    <ListBox.ItemTemplate>
      <DataTemplate>
        <StackPanel Orientation="Horizontal">
          <TextBlock Text="{Binding Path=FirstName}" Margin="0,0,4,0" />
          <TextBlock Text="{Binding Path=LastName}" />
        </StackPanel>
      </DataTemplate>
    </ListBox.ItemTemplate>
  </ListBox>

  <Grid Grid.Row="1" Margin="6" Grid.Column="1" DataContext="{Binding ElementName=lbCustomers, Path=SelectedItem}">
    <Grid.RowDefinitions>
      <RowDefinition Height="Auto" />
      <RowDefinition Height="Auto" />
      <RowDefinition Height="Auto" />
      <RowDefinition Height="Auto" />
      <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
      <ColumnDefinition Width="Auto" />
      <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>

    <TextBlock Text="First Name:" VerticalAlignment="Center" Width="75" />
    <TextBox Text="{Binding Path=FirstName}" VerticalAlignment="Center" Grid.Column="1"/>

    <TextBlock Text="Last Name:" VerticalAlignment="Center" Width="75" Grid.Row="1" />
    <TextBox Text="{Binding Path=LastName}" VerticalAlignment="Center" Grid.Row="1" Grid.Column="1" />

    <TextBlock Text="Ranking:" VerticalAlignment="Center" Width="75" Grid.Row="2" />
    <TextBlock Text="{Binding Path=Ranking}" VerticalAlignment="Center"  Grid.Row="2" Grid.Column="1" />

    <TextBlock Margin="7" Text="Addresses" FontWeight="Bold" Grid.Row="3" Grid.ColumnSpan="2" />

    <ListBox ItemsSource="{Binding Path=Addresses}" Grid.Row="4" Grid.ColumnSpan="2">
      <ListBox.ItemTemplate>
        <DataTemplate>
          <Grid>
            <Grid.ColumnDefinitions>
              <ColumnDefinition Width="100" />
              <ColumnDefinition Width="75" />
              <ColumnDefinition Width="30" />
              <ColumnDefinition Width="Auto" />
            </Grid.ColumnDefinitions>
            <TextBlock Text="{Binding Path=LineOne}" />
            <TextBlock Text="{Binding Path=City}" Grid.Column="1" />
            <TextBlock Text="{Binding Path=State}" Grid.Column="2" />
            <TextBlock Text="{Binding Path=Zip}" Grid.Column="3" />
          </Grid>
        </DataTemplate>
      </ListBox.ItemTemplate>
    </ListBox>

  </Grid>

  <Image VerticalAlignment="Top" Source="{Binding Path=Photo}" Grid.Row="1" Grid.Column="2" Margin="6" />
</Grid>

Demo-06 Typed DataTemplate

Open Demo06TypedDataTemplate.xaml.

The example demonstrates the requirements for displaying sample data when that data is rendered using a typed DataTemplate in a Resource. The key point here is that the DataTemplate is typed and in a Resource.

<m:Customer 
    xmlns:m="clr-namespace:SampleDataScenarios.Model" 
    FirstName="Alfons" LastName="Parovszky" 
    Photo="../Images/image01.png">
    <m:Customer.Addresses>
        <m:Address LineOne="125 North St" City="Greatville" State="CA" Zip="98004" />
        <m:Address LineOne="3000 1st St NE" City="Coolville" State="CA" Zip="98004" />
    </m:Customer.Addresses>
</m:Customer>

Typed DataTemplates are looked up based on DataType. If WPF cannot match the DataTemplate.DataType property with the sample data type, the DataTemplate will not be used to render the sample data. Additionally, any mismatch will also affect using the Designer Binding Builder as it won’t be able to resolve properties in the DataContext. The results of a mismatch are pictured in the right column of the two below tables.

When the sample data file Build Action is DesignDataWithDesignTimeCreatableTypes, the DataTemplate must have the d:IsDesignTimeCreatable property set to True or not set at all.

Correct Setting on Data Template When
Build Action = DesignDataWithDesignTimeCreatableTypes
Incorrect Setting on the DataTemplate When
Build Action = DesignDataWithDesignTimeCreatableTypes
Notice that ListBox is not using the typed DataTemplate to render the Address items.
<DataTemplate DataType=”{x:Type m:Address}”

d:IsDesignTimeCreatable=”True” >

—or—

<DataTemplate DataType=”{x:Type m:Address}”>

<DataTemplate DataType=”{x:Type m:Address}”

d:IsDesignTimeCreatable=”False” >

When the sample data file Build Action is DesignData, the DataTemplate must have the d:IsDesignTimeCreatable property set to False.

Correct Setting on the DataTemplate
Build Action = DesignData
Incorrect Setting on the DataTemplate
Build Action = DesignData
Notice that ListBox is not using the typed DataTemplate to render the Address items.
<DataTemplate DataType=”{x:Type m:Address}”

d:IsDesignTimeCreatable=”False” >

<DataTemplate DataType=”{x:Type m:Address}”

d:IsDesignTimeCreatable=”True” >

—or—

<DataTemplate DataType=”{x:Type m:Address}”>

Connecting Sample Data

In the below XAML the CustomerSampleData.xaml file is loaded and parsed by the d:DesignData Markup Extension and assigned to the d:DataContext for the Grid. Child controls of the Grid can data bind to properties on the DataContext and the Designer Binding Builder tooling is enabled.

<UserControl.Resources>
  <!--Because the sample data is using the DesignDataWithDesignTimeCreatableTypes build action, the 
      DataTemplate must have the property d:IsDesignTimeCreatable="True" or not at all so that the  
      types will match and be resolved correctly by the designer.-->
  <DataTemplate DataType="{x:Type m:Address}" d:IsDesignTimeCreatable="True" >
    <Grid>
      <Grid.ColumnDefinitions>
        <ColumnDefinition Width="100" />
        <ColumnDefinition Width="75" />
        <ColumnDefinition Width="30" />
        <ColumnDefinition Width="Auto" />
      </Grid.ColumnDefinitions>
      <TextBlock Text="{Binding Path=LineOne}" />
      <TextBlock Text="{Binding Path=City}" Grid.Column="1" />
      <TextBlock Text="{Binding Path=State}" Grid.Column="2" />
      <TextBlock Text="{Binding Path=Zip}" Grid.Column="3" />
    </Grid>
  </DataTemplate>

</UserControl.Resources>
<Grid d:DataContext="{d:DesignData Source=/SampleData/CustomerSampleData.xaml}">
  <Grid.RowDefinitions>
    <RowDefinition Height="Auto" />
    <RowDefinition Height="*" />
  </Grid.RowDefinitions>
  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="*" />
    <ColumnDefinition Width="*" />
  </Grid.ColumnDefinitions>

  <TextBlock Text="Demo-06 Typed DataTemplate" Grid.ColumnSpan="2" FontWeight="Bold" FontSize="14" Margin="11" />

  <Grid Grid.Row="1" Margin="6">
    <Grid.RowDefinitions>
      <RowDefinition Height="Auto" />
      <RowDefinition Height="Auto" />
      <RowDefinition Height="Auto" />
      <RowDefinition Height="Auto" />
      <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
      <ColumnDefinition Width="Auto" />
      <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>

    <TextBlock Text="First Name:" VerticalAlignment="Center" Width="75" />
    <TextBox Text="{Binding Path=FirstName}" VerticalAlignment="Center" Grid.Column="1"/>

    <TextBlock Text="Last Name:" VerticalAlignment="Center" Width="75" Grid.Row="1" />
    <TextBox Text="{Binding Path=LastName}" VerticalAlignment="Center" Grid.Row="1" Grid.Column="1" />

    <TextBlock Text="Ranking:" VerticalAlignment="Center" Width="75" Grid.Row="2" />
    <TextBlock Text="{Binding Path=Ranking}" VerticalAlignment="Center"  Grid.Row="2" Grid.Column="1" />

    <TextBlock Margin="7" Text="Addresses" FontWeight="Bold" Grid.Row="3" Grid.ColumnSpan="2" />

    <ListBox ItemsSource="{Binding Path=Addresses}" Grid.Row="4" Grid.ColumnSpan="2" />

  </Grid>

  <Image VerticalAlignment="Top" Source="{Binding Path=Photo}" Grid.Row="1" Grid.Column="1" Margin="6" />
</Grid>

Silverlight Sample Data Scenarios 

The above WPF scenarios are also valid for Silverlight and won’t be repeated here. The biggest difference between the two platforms with respect to sample data is the required pack syntax for images in sample data files.

Open either solution: CS-SampleDataScenarios or VB-SampleDataScenarios.

Rebuild solution.

The WPF samples are in the SLSampleDataScenarios project.

Demo-01 Single Customer

Open Demo01SingleCustomer.xaml.

This is an example of a single instance sample data file consumed by a form. The single instance of Customer has 2 instances of Address. Notice the assembly name; component syntax is used to identify an image in the project that has its Build Action set to Resource.

<m:Customer 
    xmlns:m="clr-namespace:SLSampleDataScenarios.Model" 
    FirstName="Alfons" LastName="Parovszky" 
    Photo="/SLSampleDataScenarios;component/Images/image01.png">
    <m:Customer.Addresses>
        <m:Address LineOne="125 North St" City="Greatville" State="CA" Zip="98004" />
        <m:Address LineOne="3000 1st St NE" City="Coolville" State="CA" Zip="98004" />
    </m:Customer.Addresses>
</m:Customer>

In the below form, the Customer type is available in the root Grid’s DataContext. This is important because the presence of d:DesignData and sample data not only feeds the DataContext to render data, but also enables the Designer tooling for creating and editing bindings in the Binding Builder.

Connecting Sample Data

In the below XAML the CustomerSampleData.xaml file is loaded and parsed by the d:DesignData Markup Extension and assigned to the d:DataContext for the Grid. Child controls of the Grid can data bind to properties on the DataContext and the Designer Binding Builder tooling is enabled.

<Grid d:DataContext="{d:DesignData Source=../SampleData/CustomerSampleData.xaml}">
  <Grid.RowDefinitions>
    <RowDefinition Height="Auto" />
    <RowDefinition Height="*" />
  </Grid.RowDefinitions>
  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="*" />
    <ColumnDefinition Width="*" />
  </Grid.ColumnDefinitions>

  <TextBlock Text="Demo-01 Single Customer" Grid.ColumnSpan="2" FontWeight="Bold" FontSize="14" Margin="11" />

  <Grid Grid.Row="1" Margin="6">
    <Grid.RowDefinitions>
      <RowDefinition Height="Auto" />
      <RowDefinition Height="Auto" />
      <RowDefinition Height="Auto" />
      <RowDefinition Height="Auto" />
      <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
      <ColumnDefinition Width="Auto" />
      <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>

    <TextBlock Text="First Name:" VerticalAlignment="Center" Width="75" />
    <TextBox Text="{Binding Path=FirstName}" VerticalAlignment="Center" Grid.Column="1"/>

    <TextBlock Text="Last Name:" VerticalAlignment="Center" Width="75" Grid.Row="1" />
    <TextBox Text="{Binding Path=LastName}" VerticalAlignment="Center" Grid.Row="1" Grid.Column="1" />

    <TextBlock Text="Ranking:" VerticalAlignment="Center" Width="75" Grid.Row="2" />
    <TextBlock Text="{Binding Path=Ranking}" VerticalAlignment="Center"  Grid.Row="2" Grid.Column="1" />

    <TextBlock Margin="7" Text="Addresses" FontWeight="Bold" Grid.Row="3" Grid.ColumnSpan="2" />

    <ListBox ItemsSource="{Binding Path=Addresses}" Grid.Row="4" Grid.ColumnSpan="2">
      <ListBox.ItemTemplate>
        <DataTemplate>
          <Grid>
            <Grid.ColumnDefinitions>
              <ColumnDefinition Width="100" />
              <ColumnDefinition Width="75" />
              <ColumnDefinition Width="30" />
              <ColumnDefinition Width="Auto" />
            </Grid.ColumnDefinitions>
            <TextBlock Text="{Binding Path=LineOne}" />
            <TextBlock Text="{Binding Path=City}" Grid.Column="1" />
            <TextBlock Text="{Binding Path=State}" Grid.Column="2" />
            <TextBlock Text="{Binding Path=Zip}" Grid.Column="3" />
          </Grid>
        </DataTemplate>
      </ListBox.ItemTemplate>
    </ListBox>

  </Grid>

  <Image VerticalAlignment="Top" Source="{Binding Path=Photo}" Grid.Row="1" Grid.Column="1" Margin="6" />
</Grid>

Demo-02 Customers DataSources Window

Open Demo02CustomersDataSourcesWindow.xaml.

This is an example of using a CollectionViewSource that has sample data as the DataContext for a form. It is assumed that the CollectionViewSource will be populated at run-time from a code-behind method.

The below sample data file has 3 instances of Customer, each with 2 instances of Address. Notice the root collection.

<m:Customers xmlns:m="clr-namespace:SLSampleDataScenarios.Model">
<m:Customer FirstName="Alfons" LastName="Parovszky" 
            Photo="/SLSampleDataScenarios;component/Images/image01.png">
        <m:Customer.Addresses>
            <m:Address LineOne="125 North St" City="Greatville" State="CA" Zip="98004" />
            <m:Address LineOne="3000 1st St NE" City="Coolville" State="CA" Zip="98004" />
        </m:Customer.Addresses>
    </m:Customer>
    <m:Customer FirstName="Lori" LastName="Penor" 
                Photo="/SLSampleDataScenarios;component/Images/image02.png">
        <m:Customer.Addresses>
            <m:Address LineOne="126 East St" City="Greatville" State="CA" Zip="98004" />
            <m:Address LineOne="3001 2st St NE" City="Coolville" State="CA" Zip="98004" />
        </m:Customer.Addresses>
    </m:Customer>
    <m:Customer FirstName="Justin" LastName="Harrison" 
                Photo="/SLSampleDataScenarios;component/Images/image03.png">
        <m:Customer.Addresses>
            <m:Address LineOne="127 West St" City="Greatville" State="CA" Zip="98004" />
            <m:Address LineOne="3002 3st St NE" City="Coolville" State="CA" Zip="98004" />
        </m:Customer.Addresses>
    </m:Customer>
</m:Customers>

In the below form, the ComboBox is used to set the CurrentItem for the CollectionViewSource. The Grid that contains the Customer data entry form has its DataContext set to the CollectionViewSource. When the ComboBox selection changes the CollectionViewSource CurrentItem, the data entry form CurrentItem will automatically change. This is one technique for providing record selection.

Connecting Sample Data

In the below XAML, the CustomersSampleData.xaml file is loaded and parsed by the d:DesignData Markup Extension and assigned to the d:DesignSource for the CollectionViewSource.

<UserControl.Resources>
  <CollectionViewSource 
    x:Key="customerViewSource" 
    d:DesignSource="{d:DesignData Source=../SampleData/CustomersSampleData.xaml}" />
</UserControl.Resources>
<Grid>
  <Grid.RowDefinitions>
    <RowDefinition Height="Auto" />
    <RowDefinition Height="Auto" />
    <RowDefinition Height="*" />
  </Grid.RowDefinitions>

  <TextBlock 
    Text="Demo-02 Customers Data Sources Window" FontWeight="Bold" 
    FontSize="14" Margin="11" />

  <StackPanel 
    Margin="6" Orientation="Horizontal" Grid.Row="1" 
    DataContext="{StaticResource customerViewSource}">
    <TextBlock VerticalAlignment="Center" Text="Select Customer:" Margin="7,0"  />
    <ComboBox Width="200" VerticalAlignment="Center" ItemsSource="{Binding}">
      <ComboBox.ItemTemplate>
        <DataTemplate>
          <StackPanel Orientation="Horizontal">
            <TextBlock Text="{Binding Path=FirstName}" Margin="0,0,7,0" />
            <TextBlock Text="{Binding Path=LastName}" />
          </StackPanel>
        </DataTemplate>
      </ComboBox.ItemTemplate>
    </ComboBox>
  </StackPanel>

  <Grid Grid.Row="2" Margin="6" DataContext="{StaticResource customerViewSource}">
    <Grid.RowDefinitions>
      <RowDefinition Height="Auto" />
      <RowDefinition Height="Auto" />
      <RowDefinition Height="Auto" />
      <RowDefinition Height="Auto" />
      <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
      <ColumnDefinition Width="Auto" />
      <ColumnDefinition Width="*" />
      <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>

    <TextBlock Text="First Name:" VerticalAlignment="Center" Width="75" />
    <TextBox Text="{Binding Path=FirstName}" VerticalAlignment="Center" Grid.Column="1"/>

    <TextBlock Text="Last Name:" VerticalAlignment="Center" Width="75" Grid.Row="1" />
    <TextBox Text="{Binding Path=LastName}" VerticalAlignment="Center" Grid.Row="1" Grid.Column="1" />

    <TextBlock Text="Ranking:" VerticalAlignment="Center" Width="75" Grid.Row="2" />
    <TextBlock Text="{Binding Path=Ranking}" VerticalAlignment="Center"  Grid.Row="2" Grid.Column="1" />

    <TextBlock Margin="7" Text="Addresses" FontWeight="Bold" Grid.Row="3" Grid.ColumnSpan="2" />

    <ListBox ItemsSource="{Binding Path=Addresses}" Grid.Row="4" Grid.ColumnSpan="2">
      <ListBox.ItemTemplate>
        <DataTemplate>
          <Grid>
            <Grid.ColumnDefinitions>
              <ColumnDefinition Width="100" />
              <ColumnDefinition Width="75" />
              <ColumnDefinition Width="30" />
              <ColumnDefinition Width="Auto" />
            </Grid.ColumnDefinitions>
            <TextBlock Text="{Binding Path=LineOne}" />
            <TextBlock Text="{Binding Path=City}" Grid.Column="1" />
            <TextBlock Text="{Binding Path=State}" Grid.Column="2" />
            <TextBlock Text="{Binding Path=Zip}" Grid.Column="3" />
          </Grid>
        </DataTemplate>
      </ListBox.ItemTemplate>
    </ListBox>

    <Image VerticalAlignment="Top" Source="{Binding Path=Photo}" Grid.RowSpan="5" Grid.Column="2" Margin="6" />
  </Grid>

</Grid>

WCF RIA Services Sample Data Scenario 

The below scenario will concentrate on surfacing design-time sample data in the Designer.

Open solution: ContosoSales.Mix10.

Rebuild solution.

Open \Views\Home.xaml.

This is an example form from the PDC 2010 RIA Services Demo. This demo has been upgraded to display design-time sample data.

The sample data file contains 2 Store records that each contains 2 Contacts.

Important
In WCF RIA Services, types deriving from Entity are not creatable. As a result, all sample data files must have their Build Action set to: DesignData and not DesignDataWithDesignTimeCreatableTypes.
Note
Blend does not support the DomainDataSource d:DesignData property. As a result, sample data applied to the DomainDataSource will not render in Blend on the art board (design surface).
<ria:DesignRIAEntitySampleDataCollection 
    xmlns:web="clr-namespace:ContosoSales.Web"
    xmlns:ria="clr-namespace:ContosoSales.SampleData">

  <web:Store City="Bellevue" StateProvince="CA" StoreID="1" StoreName="A. Datum Corporation"
            StoreImage="/ContosoSales;component/SampleDataImages/StoreFront.png" >
    <web:Store.StoreContacts>
      <web:StoreContact ContactID="55" Position="Artist" StoreID="1">
        <web:StoreContact.Contact>
          <web:Contact ContactPhoto="/ContosoSales;component/SampleDataImages/jeffhand.jpg" 
                       ContactID="55" FirstName="Alfons" LastName="Parovszky" SalesTarget="900" 
                       WorkEmail="alfons@adatum.com" WorkPhone="411" />
        </web:StoreContact.Contact>
      </web:StoreContact>
      <web:StoreContact ContactID="655" Position="Artist" Store="A. Datum Corporation" StoreID="1">
        <web:StoreContact.Contact>
          <web:Contact ContactPhoto="/ContosoSales;component/SampleDataImages/dineshku.jpg" 
                       ContactID="655" FirstName="Lori" LastName="Penor" SalesTarget="900" 
                       WorkEmail="lori@adatum.com" WorkPhone="411" />
        </web:StoreContact.Contact>
      </web:StoreContact>
    </web:Store.StoreContacts>
  </web:Store>
  <web:Store City="Bellevue" StateProvince="CA" StoreID="12" StoreName="Adventure Works"
               StoreImage="/ContosoSales;component/SampleDataImages/StoreFront.png" >
    <web:Store.StoreContacts>
      <web:StoreContact ContactID="15" Position="Sales" StoreID="2" Store="Adventure Works">
        <web:StoreContact.Contact>
          <web:Contact ContactPhoto="/ContosoSales;component/SampleDataImages/jeffhand.jpg" 
                       ContactID="15" FirstName="Justin" LastName="Harrison" SalesTarget="000" 
                       WorkEmail="justin@adventure-works.com" WorkPhone="411" />
        </web:StoreContact.Contact>
      </web:StoreContact>
      <web:StoreContact ContactID="655" Position="Artist" Store="Adventure Works" StoreID="1">
        <web:StoreContact.Contact>
          <web:Contact ContactPhoto="/ContosoSales;component/SampleDataImages/dineshku.jpg"
                       ContactID="655" FirstName="Mark" LastName="Harrington" SalesTarget="900" 
                       WorkEmail="mark@adventure-works.com" WorkPhone="411" />
        </web:StoreContact.Contact>
      </web:StoreContact>
    </web:Store.StoreContacts>
  </web:Store>
</ria:DesignRIAEntitySampleDataCollection>

Another important distinction is that the root collection must derive from List<Entity>. This is a requirement of RIA Services. Developers must create a class similar to the below class to act as a container for RIA Services sample data objects. Note, this collection does not actually care which type of entity is in the collection so long as the object derives from Entity.

namespace ContosoSales.SampleData {
    public class DesignRIAEntitySampleDataCollection : 
          List<System.ServiceModel.DomainServices.Client.Entity> {

        public DesignRIAEntitySampleDataCollection() { }
    }
}

This Store class comes from the code that Visual Studio generates in the Silverlight client application. This is contained in the hidden Generated_Code folder.

public sealed partial class Store : Entity

Connecting Sample Data

Sample data in a RIA Services application is applied to the d:DesignData property of the DomainDataSource.

<riaControls:DomainDataSource 
    SubmittedChanges="storeDomainDataSource_SubmittedChanges"  Name="storeDomainDataSource" AutoLoad="True"
    LoadedData="storeDomainDataSource_LoadedData" 
    d:DesignData="{d:DesignData Source=../SampleData/RIASampleData.xaml}"
    QueryName="GetStoresQuery" FilterOperator="Or">
    <riaControls:DomainDataSource.DomainContext>
        <my:ContactContext />
    </riaControls:DomainDataSource.DomainContext>
    ...
</riaControls:DomainDataSource>

The Home.xaml file listing is long, nested and complex so I won’t display the XAML here.

The way the Home UserControl works at design-time is very similar to the previous WPF or Silverlight examples. The major difference is that the DomainDataSource is the control that receives the sample data. From here, other CollectionViewSources can “dot” into the data exposed by the Data property to populate their CollectionView and ultimately the bound UI objects.

Have a look at the below storeStoreContactsViewSource CollectionViewSource. Its Source is set to the Data.StoreContacts. In this case, Data is actually pointing to the selected Store from the left hand ListBox in the UI. The below Grid contains the data entry form on the right hand side of the form. When the ListBox selection changes the DataContext of the data entry form changes to the SelectedItem in the ListBox.

<CollectionViewSource 
    x:Key="storeStoreContactsViewSource" 
    Source="{Binding Path=Data.StoreContacts, ElementName=storeDomainDataSource}" />

 

<ListBox 
    ItemsSource="{Binding Source={StaticResource storeStoreContactsViewSource}}" 
    Name="storeContactsListBox" Style="{StaticResource ContactListBox}" />

 

<Grid BindingValidationError="Home_BindingValidationError" 
    DataContext="{Binding Source={StaticResource storeStoreContactsViewSource}}" Name="grid1">

This UI synchronization was accomplished without a single line of code.

Choosing Sample Data Loading Technique 

From the document you can see there are a number of ways to structure your applications and thus load sample data. One of the goals for the Design-Time Sample Data Feature for Visual Studio 2010 was to not limit or box developers in from using a technique that made business sense for the type of application they are writing. For example, many developers like the power of CollectionViewSources while other developers prefer to have their XAML files DataContext set to a ViewModel. This feature combined with the above techniques easily handles these and most other scenarios.

Using d:DesignData with a corresponding XAML Sample Data file is the recommended technique for surfacing sample data in WPF and Silverlight line of business applications. This technique surfaces design-time instances of your data classes and enables the Designer Binding Builder tooling. None of the sample data files or design-time XAML is compiled into your applications, making this technique simple and clean.

Choosing to surface sample data using d:DesignData leaves open endless possibilities for your application architecture and in-fact decouples sample data from the rest of your application.

However, as a developer you are not limited to just d:DesignData as the WPF Demo-03 Customer ViewModel demonstrated.

Comments 

Microsoft values your opinion about our products and documentation. In addition to your general feedback it is very helpful to understand:

  • How the above features enable your workflow
  • What is missing from the above features that would be helpful to you

Thank you for your feedback and have a great day,

Fonte: http://blogs.msdn.com/b/wpfsldesigner/archive/2010/06/30/sample-data-in-the-wpf-and-silverlight-designer.aspx

Autor: Karl Shifflett
Expression Team

Tips and Tricks for working with the WPF and Silverlight Designer in Visual Studio 2010

Tip 1: Install Silverlight 4 Tools even if you are building WPF apps 

The Silverlight 4 Tools for Visual Studio 2010 contain many features and several bug fixes that are useful for WPF developers too (see this blog post for details of the features) – you should install it even if you are not working on Silverlight applications.

Tip 2: The Properties Window works when just editing XAML too. 

The Properties Window has a lot of useful features such as the Binding and Resource Pickers, Go To Definition, and various useful editors like the Brush Editor. Lots of people assume the only time you can use these features is when you’re working on the Design pane – but that’s not true! Open up the Properties Window next time you are in XAML view for your Page or Window, and you’ll see that the XAML element your cursor is in is shown in the Properties Window, so you can use those features there too. You can see this tip illustrated in this video.

Tip 3: Getting the Properties Window to work when working with Resource Dictionaries and App.xaml 

Closely linked to Tip 1 – for reasons of performance, by design the WPF and Silverlight Designer does not load the Properties Window (or the design view) for app.xaml and resource dictionary XAML files.

However if you want to make use of the useful Properties Window features (such as the Go To Definition feature for instance) when in such a file, all you need to do is activate the design pane (use the splitter bar controls to activate split view, then click anywhere on the grey “Intentionally Left Blank” design pane screen). Then you can shift the splitter so that only a tiny part of the designer is visible to avoid wasting screen real-estate.

The designer will remember this setting on a per-file basis, so next time you open that file, it will activate the designer too. You can see this tip illustrated in this video.

Tip 4: Use Sample Data for a happier design experience in your templates 

You may have had the frustrating experience of attempting to edit an item template with no data in it – it is nearly impossible to work out how your design will actually look based on the design-time experience, especially when your design sizes to the content it is bound to. Fortunately it is now possible to add sample data to your application. We show you how in this video, and you should also check out Sample Data in the Visual Studio 2010 WPF and Silverlight Designer for more details. This not only makes this sort of design easier, it can also help you avoid typos in your data binding statements by enabling the use of the Binding Builder.

Tip 5: Quick way to add the d: namespace for Sample Data 

When working with Sample Data, you will need the d: namespace in your XAML. Entering the exact namespace and other required document heading definitions such as mc:ignorable for this is a pain – but you don’t have to!

If you need to add these definitions to a Page, Window or UserControl in the designer:

  • Select the root-most item (see Tip 8 below for selection tips)
  • Click the root size mode button twice

Clicking the root size mode button twice, will insert the necessary XAML header information but leave your design’s root width/height behavior unaltered. For detailed information about the root size mode button please see this blog post.

Tip 5: Pressing Alt key while move/resize hides the snaplines: 

For a complex form, move/resize of an element on the designer surface might result in a lot of snaplines being shown. If you don’t want to see them, you can easily turn them OFF by pressing and holding the ALT key during drag move/resize.

Tip 6: Pressing the Spacebar lets you Pan the Design Surface with the Mouse 

When you have a large design or are zoomed in, it can be very helpful to be able to pan with the mouse to get to the area you want to view. When you’re over the Design Surface, just press the Spacebar and move your mouse to get panning.

Tip 8: Easy ways to select hard-to-select things on the design surface 

Most of the time you can just click on an object to select it. Upon selection you’ll notice that the element is also selected in the XAML Editor, Properties Window and Document Outline.

However there are tricky scenarios where this isn’t always possible to click on an object to select it. In those cases, these tips will come in handy:

Use Tab Key To Go To The Next Control On Design Surface

When a control on the design surface is selected, pressing the Tab key will change selection to the next control in the tabbing order.  Pressing SHIFT+TAB will select the previous control in the tabbing order.

Pressing ESC Key or right click and use the Selection menu to Select Parent Control

With a control selected on the design surface, pressing the ESC key will cause selection to be changed it its parent control.  Continued pressing will continue to change selection to the next parent control. There’s also a right-click menu action that lets you quickly select parent items of the selected item.

Use the Document Outline or the Path Control to view the XAML tree structure and select objects

The Document Outline window has a very useful view of the XAML tree and can be used to select any point in the tree. The Path Control at the bottom of the XAML editor also allows selection of parent controls (and children via the button at its right-hand end).

Tip 9: Use Bring to Front / Send to Back to set tab order within a panel 

Because WPF and Silverlight use the Document Order (the order in which elements appear in the XAML) to set both Z Order AND Tab Order in a document by default, you can use the right click context menu to move items in a form forward and backward in the Tab Order as well as changing their Z-order. This is significantly easier than individually setting the Tab Order of items one by one.

Tip 10: Use the new multi-monitor support to open my XAML and Design panes in separate windows 

Visual Studio 2010 has great multi-monitor support with tear-off windows etc. We would like to add real support for tearing off the two parts of the split view of the WPF and Silverlight Designer in a future release – meanwhile there are a couple of workarounds:

If your goal is multi-monitor with code on the right and design surface on the left (for instance), then you can maximize VS2010 across both screens, set the splitter to be VERTICAL (there are buttons in the splitter bar that let you do this), then place the splitter at the join between the two screens (quickest approach)

If you want more flexibility, you can:

  • Open a second tab group (right click on a tab and open new Vertical Tab Group)
  • Open the XAML as normal in one of the tab groups
  • Open the XAML again using “Open With”…”Source Code Editor”
  • Put the XAML and the designer in different tab groups, maximize the designer in the first, and now you’ve got full, tearable-window, multi-monitor friendly goodness for your XAML and designer views

Fonte: http://blogs.msdn.com/b/wpfsldesigner/archive/2010/06/30/tips-and-tricks-for-working-with-the-wpf-and-silverlight-designer-in-visual-studio-2010.aspx#tip1

Autor: Karl Shifflett