DesignDataじゃなくて、サンプル用に実物の固定データが欲しいのです。

サンプルアプリケーションを作るときに思うこと。
サンプル用のデータを手っ取り早く作りたい。手っ取り早く作るためにXamlで書きたい。

最初はViewModel作った後にViewModelのコンストラクタとかで作ったり読み込ませたりしてたけど、
考えてみるとデザイン用には

<UserControl d:DataContext="{d:DesignData /SampleData.xaml}" />

みたいに書けるのだから、デザイン時だけじゃなくて実データとしても似たような書き方できないかなと思った。

しかし、

<UserControl DataContext="{Source=/SampleData.xaml}" />

みたいな書き方はできず、下記のようにResouceDictionaryをかまさなければならないよう。

■SampleData.xaml

<ResourceDictionary xmlns:my="clr-namespace:SilverlightApplication22" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <my:SampleViewModel x:Key="SampleData">
        <my:SampleViewModel.Drivers>
            <my:Driver Name="マンセル" Point="120"/>
            <my:Driver Name="セナ" Point="100"/>
            <my:Driver Name="プロスト" Point="80"/>           
        </my:SampleViewModel.Drivers>        
    </my:SampleViewModel>
</ResourceDictionary>

■MainPage.xaml

<UserControl x:Class="SilverlightApplication22.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    >
    <UserControl.Resources>
        <ResourceDictionary Source="/SilverlightApplication22;component/SampleData.xaml" />
    </UserControl.Resources>
   
    <Grid x:Name="LayoutRoot" Background="White" DataContext="{StaticResource SampleData}">
        <ListBox ItemsSource="{Binding Drivers}" >
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding Name}" />
                        <TextBlock Text="{Binding Point}" Margin="10,0,0,0"/>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
</UserControl>

■ViewModel

using System.Collections.Generic;

namespace SilverlightApplication22
{
    public class SampleViewModel
    {
        public List<Driver> Drivers { get; set; }

        public SampleViewModel()
        {
            // newしとかないと「コレクション プロパティ '__implicit_items' が null です」というわけのわからないメッセージで怒られる
            Drivers = new List<Driver>();
        }
    }

    public class Driver
    {
        public string Name { get; set; }
        public string Point { get; set; }
    }
}

WPFのことだけ考えれば良い場合はXPathでBindすればViewModelクラス自体作る必要が無いのだろうけど、
Silverlightは残念ながらXPathでのBindが使えない(だったと思う)

同じXamlを使うのにでWPFSilverlightの書き方を変えるなんて器用なことはできるだけ(しょうが無いのは別だけど)したくないので
今後はこのやり方が中心になるかなぁ・・・。