datacontext – Silverlight User Control in MainPage.xaml – Education Career Blog

I’m currently investigating building a User Control in a Silverlight Project in Expression Blend 4. The control has an associated set of sample data for the User Control, and the data is appearing correctly in the User Control.

When I place the User Control on the main page, the sample data does not appear in the User Control. Is this correct behaviour, or am I setting/not setting something? What I am finding odd is that when I edit the User Control, the data appears in the Main Page alongside a Rebuild Indicator (Yellow Exclamation mark). When I rebuild, the data disappears again.

This is the Main Page Code:

xmlns:d="" xmlns:mc="" xmlns:local="clr-namespace:SilverlightApplication2" mc:Ignorable="d"
Width="1200" Height="640">
    <local:MultiDayViewModel x:Key="MultiDayViewModelDataSource" d:IsDataSource="True"/>

<Grid x:Name="LayoutRoot" Background="White" d:DataContext="{d:DesignData /SampleData/TestSampleData.xaml}">
        <RowDefinition Height="0.128*"/>
        <RowDefinition Height="0.872*"/>
    <StackPanel Margin="0,24,8,8" HorizontalAlignment="Right" Width="318" Orientation="Horizontal">
        <Button Content="Daily"/>
        <Button Content="Weekly"/>
    <local:MultiDayView x:Name="MultiDayView" Margin="8" Grid.Row="1" DataContext="{Binding Calenar, Source={StaticResource MultiDayViewModelDataSource}}"/>

Any thoughts or directions would be appreciated.



You are using d:DataContext, which only appears in design mode. When you place the control inside MainPage, it is interpreted by Blend as being in runtime mode, so the data does not appear, so this is expected behavior.

When you create the sample data for you control in Blend you can specify whether you want this sample data to be used during runtime as well, or you can simply set the DataContext property instead of or in addition to the d:DataContext property.

The following image shows how you can enable sample data during runtime, when you create the sample data source from Blend:

Enable sample data when application is running

When you select the option called “Enable sample data when application is running”, your XAML looks like this:

        Width="640" Height="480">
            <DataTemplate x:Key="DataTemplate1">
                <CheckBox Content="{Binding Property1}" IsChecked="{Binding Property2, Mode=TwoWay}"/>

        <Grid x:Name="LayoutRoot" Background="White" DataContext="{Binding Source={StaticResource SampleDataSource}}">
            <ItemsControl ItemsSource="{Binding Collection}" ItemTemplate="{StaticResource DataTemplate1}" Margin="50"/>

This will show your sample data for both design time and runtime.

Leave a Comment