かずきのBlog@hatena

すきな言語は C# + XAML の組み合わせ。Azure Functions も好き。最近は Go 言語勉強中。日本マイクロソフトで働いていますが、ここに書いていることは個人的なメモなので会社の公式見解ではありません。

MVVM Light + ReactiveProperty to @kamebuchi さん

今日はデベロッパーサミット2012にいってきたのですが、そこで抱かれたい男No1で有名な@kamebuchiさんにお会いできました。

訓練されたあじゅらーの人にとっては有名なBlogだと思います。私もAzureの情報を探してていきつくことが多々あります。そんな@kamebuchiさんがMVVM Light + Reactive Propertyで画面にバインドできないということだったので帰宅して試してみます!!

プロジェクトの準備

  • WP7アプリケーションを作成します
  • MVVM LightをNuGetから導入します。
  • Reactive Property for Rx StableをNuGetから導入します

MainViewModelのコードを以下のようにします

using GalaSoft.MvvmLight;
using Codeplex.Reactive;

namespace PhoneApp1.ViewModel
{
    public class MainViewModel : ViewModelBase
    {
        public ReactiveProperty<string> Name { get; private set; }

        public MainViewModel()
        {
            this.Name = new ReactiveProperty<string>("kamebuchi");
        }
    }
}
ビルドするとこんなエラーがデザイナで起きるようになります

これはきっとVisual Studio側の不具合と思われ

ほっといてバインドします。

デザイナが死ぬので手打ち(インテリセンスも死ぬので実力が試される)

<phone:PhoneApplicationPage 
    x:Class="PhoneApp1.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    shell:SystemTray.IsVisible="True"
    DataContext="{Binding Source={StaticResource Locator}, Path=Main}">
    <!-- ↑ ViewModelLocatorからViewModelをDataContextにBinding -->
    
    <!--LayoutRoot は、すべてのページ コンテンツが配置されるルート グリッドです-->
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <!--TitlePanel は、アプリケーション名とページ タイトルを格納します-->
        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock x:Name="ApplicationTitle" Text="マイ アプリケーション" Style="{StaticResource PhoneTextNormalStyle}"/>
            <TextBlock x:Name="PageTitle" Text="ページ名" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>

        <!--ContentPanel - 追加コンテンツをここに入力します-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <!-- ReactivePropertyの値をバインド -->
            <TextBlock Text="{Binding Name.Value}"/>
        </Grid>
    </Grid>
</phone:PhoneApplicationPage>
実行するとバインドできてます!

まとめ

ということで、問題なくバインドできました。(IDataErrorInfo継承してるとデザイナが死ぬという問題はありますが…)