Generate RSS Feed in ASP.Net

RSS feed is an xml formatted document that gives user the capability to read frequently updated contents on our websites without visiting our site. RSS feed has become one of the most sophisticated mechanism to share information on the internet world. It is one of the web 2.0 features which allows users to read their relevant information’s available on the internet. All we need to do is, get the RSS feed URL from different sites of our interest and subscribe it on our RSS reader. Before moving to actual implementation of RSS feed we will understand the format of RSS feeds that a RSS reader can consume.

For example, CodeDigest Rss feed will look like,

<?xml version=”1.0″ encoding=”utf-8″ ?>

<rss version=”2.0″>

  <channel>

  <title>CodeDigest.com Latest Articles</title>

  <link>http://www.codedigest.com</link&gt;

  <description>Latest articles hosted on CodeDigest.com.</description>

  <item>

  <title>Useful Datagrid Tips</title>

  <description>There are some frequent queries that are being asked in most of the forums and UG’s regarding datagrid. I have compiled a list of useful tips from my previous posts and posted it here.</description>

  <link>http://www.codedigest.com/Articles/ASPNET/77_Useful_Datagrid_Tips.aspx</link&gt;

  <pubDate>4/29/2008 9:47:12 AM</pubDate>

  </item>

</channel>

  </rss>

As we can see the above XML, the whole contents are packed inside <rss> tag. The actual information about the posts is kept inside <item> tag which in turn is packed inside a <channel> tag.  Moving forward this article will help us understand constructing an RSS feeds for our asp.net sites.

What we need to do?

Generating RSS feed for our website is nothing but emitting the frequently updated data in the above specified XML format. It can be done by constructing the XML document and performing a Response.Write of the constructed XML document.

 What should we use?

Our requirement can be achieved by performing a Response.Write on an ASPX page. But, in this article we will generate our RSS feed using HttpHandler instead of an ASPX page. There are some advantages in using HttpHandler over an ASPX pages, an ASPX page will have a series of events like OnInit, Page load, etc  which is not at all required in our case. These page level events are over head since we just want to get the data from database and construct a XML document and output the raw xml.

Implementation

With the RSS feed XML format in mind, we can construct XML using XmlTextWriter class. Include an HttpHandler to our project by right clicking solution and clicking “Add New Item”. Refer the below figure.

 

RSS.ashx

<%@ WebHandler Language=”C#” %>

 

using System;

using System.Web;

using System.Data;

using System.Text;

using System.Xml;

using DataAccess;

  public class Rss : IHttpHandler {

     ArticleDAO articleDAO = new ArticleDAO();

     public void ProcessRequest (HttpContext context) {

         // Clear any previous output from the buffer

           context.Response.Clear();

                   context.Response.ContentType = “text/xml”;

               XmlTextWriter cdRSS = new XmlTextWriter(context.Response.OutputStream, Encoding.UTF8);

 

        cdRSS.WriteStartDocument();      

 

        cdRSS.WriteStartElement(“rss”);

 

        cdRSS.WriteAttributeString(“version”, “2.0”);       

 

        cdRSS.WriteStartElement(“channel”);

 

        cdRSS.WriteElementString(“title”, “CodeDigest.com Latest Articles”);

 

        cdRSS.WriteElementString(“link”, “http://www.codedigest.com&#8221;);

 

        cdRSS.WriteElementString(“description”, “Latest articles hosted on CodeDigest.com.”);

 

        cdRSS.WriteElementString(“copyright”, “Copyright 2008 – 2009 CodeDigest.com. All rights reserved.”);

 

       //Connect database to get the data

        DataTable dtArticles = articleDAO.GetArticlesForRss();

 

        for (int i = 0; i < dtArticles.Rows.Count; i++)

        {

       //Build Item tags with the data from database

            cdRSS.WriteStartElement(“item”);

 

            cdRSS.WriteElementString(“title”, dtArticles.Rows[i][“Title”].ToString());

 

            cdRSS.WriteElementString(“description”, dtArticles.Rows[i][“description”].ToString());

 

            cdRSS.WriteElementString(“link”, “http://”+ context.Request.Url.Host + dtArticles.Rows[i][“URL”].ToString());

 

            cdRSS.WriteElementString(“pubDate”, dtArticles.Rows[i][“ApprovedOn”].ToString());

 

            cdRSS.WriteEndElement();

        }

 

        cdRSS.WriteEndElement();

 

        cdRSS.WriteEndElement();

 

        cdRSS.WriteEndDocument();

 

        cdRSS.Flush();

 

        cdRSS.Close();

 

        context.Response.End();     

 

    }

 

    public bool IsReusable {

        get {

            return false;

        }

    }

}

Font:  http://www.codedigest.com/Articles/ASPNET/86_Generate_RSS_Feed_in_ASPNet.aspx 

*********************************************

Soluções em desenvolvimento de sistemas com a DANRESA Consultoria.

Anúncios

DANRESA Implementa e Customiza Sharepoint para PME

A DANRESA Consultoria de Informática Implementa e Customiza o Microsoft Sharepoint 2010 para PME

Saiba o que esta poderosa ferramenta pode fazer pela sua empresa e como a DANRESA pode ajudar para que seja aderente ao seu negócio.

A Plataforma de Colaboração Corporativa para a Empresa e a Internet.

O Microsoft SharePoint facilita o trabalho em conjunto.  Utilizando o SharePoint, os seus colaboradores podem configurar sites da Web para compartilhar informações, gerenciar documentos e publicar relatórios que ajudam na tomada de melhores decisões.

Vantagens para profissionais de TI
O SharePoint oferece uma infraestrutura avançada fácil de implementar que pode ajudar a tornar a sua empresa mais produtiva. Administração e gestão centralizadas, sistema pronto para responder a qualquer necessidade de negócios.

Vantagens para desenvolvedores
Criação de aplicações e componentes personalizados. Graças a ferramentas familiares, é fácil criar Componentes Web, tipos de conteúdos externos e atividades de fluxo de trabalho para utilização em soluções baseadas no SharePoint.

Vantagens para usuários finais
Acesse pessoas e informações corretas, no momento certo, e tome melhores decisões. Total integração com o Microsoft Office.

Com o SharePoint seus colaboradores podem:

  • Compartilhar ideias e habilidades;
  • Criar soluções personalizadas para suprir necessidades específicas;
  • Encontrar as informações empresariais corretas para tomar melhores decisões.

Conheça algumas das capacidades do SharePoint:

Sites:

  • Compartilhar e publicar informações facilmente.
  • Trabalhar com outras tecnologias familiares. Qualquer pessoa pode acessar e compartilhar conteúdos, no escritório ou na rua.
  • Focalização do público-alvo, suporte de interface em vários idiomas e marca do usuário.
  • Acessar os sites do SharePoint 2010 a partir de dispositivos móveis utilizando um micronavegador moderno e um gateway de acesso.
  • Aumentar o rendimento através de marketing digital na Internet.

Composições:

  • Centraliza e implementa as bases de dados do Access e planilhas do Excel.
  • Permite um acesso controlado a dados da empresa.
  • Implementa Soluções Sandbox seguras sem comprometer a saúde da plataforma.

Percepções:

  • Classificações e painéis de controle interativos.
  • Características de relatório e análise avançadas,  fáceis de utilizar.
  • Associações de indicadores-chave com estratégias específicas.
  • Visualização de informações  pertinentes utilizando a Árvore de Decomposição.
  • Análise de informações atualizadas em tempo real.

Comunidades:

  • Ferramentas de colaboração.
  • Única plataforma avançada.
  • Funcionamento integral com Microsoft Office, Exchange Server, Office Communications Server, SQL Server e Dynamics.
  • Compatível com padrões abertos, uso de  aplicações e sistemas de terceiros.
  • My Profile (Meu Perfil) – informações sobre funcionários, informações de contato e projetos anteriores.

Conteúdo:

  • Gestão de conteúdos empresariais (ECM) fácil para todos.
  • Aumento da produtividade e  valor das informações.
  • Classificação de conteúdos, cumprimento de planos de retenção, declaração de registros e aplicação de normas legais.

Busca:

  • Pesquisa na intranet, procura de pessoas e plataforma para a criação de aplicações com busca integrada.
  • Procura de Usuários e Habilidades.
  • Compartilhamento de ideias e habilidades para solucionar problemas, melhorar processos e promover a inovação.
  • Navegação orientada por metadados.

Cases:

Sem Parar
Utilização do Sharepoint como Intranet, ambiente colaborativo.
Instituto Ayrton Senna
Utilização do Sharepoint como Intranet, controle de documentos.

Search WebPart for Sharepoint 2010

By tdomf_6998b, on October 19th, 2010
This is a free webpart. Below is the complete code. Enjoy!

In SharePoint 2010, you can use the query object model to build custom
search
Web Parts and search applications. This object model allows you to
query against SharePoint Server search as well as to FAST Search Server 2010 for
SharePoint.

The FullTextSqlQuery class available in the object model allows you to build
complex search queries based on SQL syntax however, the KeywordQuery class can
be used to issue search queries based on simple query syntax. With Fast Search
Server 2010, this class can also be used to run queries based on the Fast Query
Language (FQL), which supports advanced queries in enterprise environments.

The example below demonstrates using the query object model to issue a search
query based on a keyword search with the KeywordQuery class. This example is
built as an application page with a text input field called txtSearch, a button
for submitting the query called btnSearch, and an SPGridView called
searchGrid.

Please Note : Before you can run search queries, you also need to specify the
search server that should be used for indexing in Central Administration, under
Application Management -> Databases -> Manage Content Databases ->
[Your content DB] > Search Server.

using System;
using Microsoft.SharePoint;
using
Microsoft.SharePoint.WebControls;
using System.Data;
using
Microsoft.Office.Server;
using Microsoft.Office.Server.Search;
using
Microsoft.Office.Server.Search.Query;

namespace Apress.SP2010.Layouts.CustomSearch
{
public partial class
ApplicationPage1 : LayoutsPageBase
{
protected void Page_Load(object
sender, EventArgs e)
{
if
(!IsPostBack)
{
SetGridColumns();
}
}

// The event is called when the search button is pressed
protected void
btnSearch_Click(object sender, EventArgs e)
{
DataTable search = new
DataTable();

using (SPSite site = new
SPSite(SPContext.Current.Web.Site.Url))
{
KeywordQuery query = new
KeywordQuery(site);

query.ResultsProvider = Microsoft.Office.Server.Search.Query.

SearchProvider.Default;

query.ResultTypes = ResultType.RelevantResults;

query.KeywordInclusion = KeywordInclusion.AllKeywords;

query.QueryText = txtSearch.Text;

ResultTableCollection results = query.Execute();

if (results.Count > 0)
{

ResultTable relevant = results[ResultType.RelevantResults];

search.Load(relevant);

DataView view = new DataView(search);

// Fill the SPGridView defined in the page markup

searchGrid.DataSource = search;

searchGrid.DataBind();
}}}

private void SetGridColumns()
{
SPBoundField fieldTitle = new
SPBoundField();

fieldTitle.HeaderText = “Title”;

fieldTitle.DataField = “Title”;

SearchGrid.Columns.Add(fieldTitle);

SPBoundField fieldPath = new SPBoundField();

fieldPath.HeaderText = “Path”;

fieldPath.DataField = “Path”;

SearchGrid.Columns.Add(fieldPath);

SPBoundField fieldAuthor = new SPBoundField();

fieldAuthor.HeaderText = “Edited”;

fieldAuthor.DataField = “Write”;

SearchGrid.Columns.Add(fieldAuthor);
}}}

In the above code, the OnClick handler for the button creates a KeywordQuery
object and passes the text from the text field to the QueryText property. After
calling Execute, the results are available through the ResultTable at the index
ResultType.RelevantResults in the returned ResultTableCollection. Using a
DataTable, these results are bound to the SearchGrid for display. The relevant
table columns are bound using the SetGridColumns method during Page_Load.

Saiba mais sobre os recursos do Sharepoint

Expression Web 3.0 and 4.0 Articles Link List

A couple of days ago, we had posted a Link List of ASP.NET MVC, ASP.NET and jQuery Articles and Silverlight, .NET 4.0 and LINQ Articles Link List published on this site in the last 6 months. This week, we will be covering the articles on Expression Web 3 and 4. This list should help you stay updated with the content you might have missed on this site. Here’s the list:What’s new in Microsoft Expression Web 4? – In this article we will explore the new features available in Expression Web 4

Designing websites for accessibility in Expression Web – Part I – This article gives you an idea and tips of how to make your web site accessible

Designing websites for accessibility in Expression Web – Part II – In this article we will explore the Accessibility Checker feature of Expression Web and how to use it to test your website accessibility

Using jQuery to Open External Links in a New Window – Expression Web – This article is about using jQuery to open external links on your page in a new window

Changing the appearance of a picture in Microsoft Expression Web 3 – In this article we will be exploring only those options that enable you to edit a picture’s appearance on the webpage.

How to use Personal Web Packages in Microsoft Expression Web – A Personal Web Package contains pages, files and folders. In Expression Web, you can export or package a website or a group of files or folders so that someone else can import it and use it in their websites. In this article we will learn more about these web packages, how to create them and use them.

Setting the Frame properties in Expression Web 3 – In this article, we will look at various properties of frames

Setting the Page Editor Options in Microsoft Expression Web 3 (Part I) – With Page Editor Options you can specify settings for various Microsoft Expression Web features. In this article we will explore few tabs of the Page Editor Options dialog box.

Setting the Page Editor Options in Microsoft Expression Web 3 (Part II – Code Formatting) – With Page Editor Options you can specify settings for various Microsoft Expression Web features. In this article we will explore some more tabs of the Page Editor Options dialog box.

Setting the Page Editor Options in Microsoft Expression Web 3 (Part III – CSS tab) – In this article, we will explore the various CSS options that help you control how styles are generated by Microsoft Expression Web 3.

Setting the Page Editor Options in Microsoft Expression Web 3 (Part IV) – With Page Editor Options you can specify settings for various Microsoft Expression Web features. In this article we will explore few tabs of the Page Editor Options dialog box.

Creating scrollable content area using CSS overflow property in Expression Web – In this article, we will create scrollable content area by using the CSS overflow property for HTML divs in Expression Web

Preview Tools in Microsoft Expression Web 3 – Microsoft Expression Web 3 has built-in preview tools which you can use to test your web pages while designing them. In this article, I have listed the preview tools focusing more on the Development Server.

Explore CSS Properties Panel in Expression Web 3 – Expression Web 3 Panels (known as task panes in earlier versions) contain all the tools you would require while developing you web pages. Panels have been classified according to the type and categories of tools. All the panels are available in the Panels menu in Expression Web 3. In this article, we will explore the CSS Properties panel.

Expression Web Queries – Queries in Expression Web to search and replace a particular pattern or factor could be required often while developing a website. The Find and Replace dialog box in Expression Web has much to offer, than the traditional find and replace mechanism. You can create queries for the same. In this article we would take a deep insight into how to create such queries to pinpoint any misses in the code and search and replace intelligently.

Open and publish a live website in Microsoft Expression Web 3 – Expression Web lets you create website live on the server as well as create it offline and then upload to the server. Let us explore how to use each of these options to open and publish your website using FTP.

I hope you liked this list and I thank you for viewing it.

Fonte: http://www.dotnetcurry.com/ShowArticle.aspx?ID=541&utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+netCurryRecentArticles+(.NET+Curry%3A+Recent+Microsoft+ASP.NET%2C+Silverlight%2C+WinForms%2C+Vista%2C+C%23%2C+VB.NET+Articles)&utm_content=Google+Reader

Using Dynamic Views In ASP.NET MVC 2

A really cool addition to ASP.NET MVC 2 is the ability to use the dynamic type as the object passed into the view. This is also known as a dynamic view. If you create a new view and don’t create a strongly typed view, out of the box, the MVC framework will make the view inherit from the ViewPage class, but the generic type will be dynamic, like this:

<%@Page Language=”C#” MasterPageFile=”~/Views/Shared/ViewMasterPage.Master” Inherits=”System.Web.Mvc.ViewPage”
<dynamic>”%>

Using the dynamic type is good because it allows you to create your objects on the fly. The downside of this is because the view is not strongly typed, you don’t get the compile time checking. For me compile time checking is a compelling reason to use strongly typed views.
In this example, I’m going to pass a collection of time zones into the view as a dynamic object to the view. To see this in action, I’m going to create a small ASP.NET MVC 2 website. If you haven’t got Microsoft Visual Studio 2010, you can download the Express edition here.
To begin, let’s add the view straight away. Normally you would do this after you have defined your action, but that’s not the focus of this article. By adding a view that is not strongly, we get to use the dynamic type. Here’s the view:
AddView
The HTML that’s added inherits from the ViewPage class, but the generic type is dynamic:
<%@Page Title=”” Language=”C#” MasterPageFile=”~/Views/Shared/ViewMasterPage.Master” Inherits=”System.Web.Mvc.ViewPage”
<dynamic>”%>
Cool huh?! Now I can add a dynamic object. I’m going to be displaying the list of time zones on your computer in a drop down list. Here’s the code:
<asp:ContentID=”Content2″ ContentPlaceHolderID=”MainContent” runat=”server”>
<%:Html.DropDownList(“DisplayName”,(IEnumerable=””
<SelectListItem> )Model.TimeZones) %>
</asp:Content>
I can access the dynamic type via the Model property which is available to the view by default. If you compiled this now, even though I haven’t created a real object, it will still compile.
Ok let’s add code to the controller to return the list of time zones. I’m adding this to the HomeController. Here’s the code below:
C#

public ActionResult GetTimeZones()
{
dynamic viewData = new ExpandoObject();
viewData.TimeZones = from p in TimeZoneInfo.GetSystemTimeZones()
select new SelectListItem
{
Text = p.DisplayName,
Value = p.Id
};
return View(“Index”, viewData);
VB.NET

Public Function GetTimeZones() As ActionResult
Dim viewData As Object = New ExpandoObject()
viewData.TimeZones = From p In TimeZoneInfo.GetSystemTimeZones()

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