mvvm light toolkitの導入①
まずはMVVMのフレームワークの導入から。
Visual Studioの拡張機能で「MVVM light for VS2015」を導入。
その後、新規プロジェクト作成でテンプレートから作成。
作成されたソースを確認。
まず、MainWindow.xaml。
<Window x:Class="MvvmLightIntroduction.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:ignore="http://www.galasoft.ch/ignore" mc:Ignorable="d ignore" Height="300" Width="300" Title="MVVM Light Application" DataContext="{Binding Main, Source={StaticResource Locator}}"> <Window.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="Skins/MainSkin.xaml" /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Window.Resources> <Grid x:Name="LayoutRoot"> <TextBlock FontSize="36" FontWeight="Bold" Foreground="Purple" Text="{Binding WelcomeTitle}" VerticalAlignment="Center" HorizontalAlignment="Center" TextWrapping="Wrap" /> </Grid> </Window>
まず、ここでよく分からないのが以下のコード。
mc:Ignorable="d ignore"
これについては、一応説明のページがあった。
mc:Ignorable 属性
katsuyuzu.hatenablog.jp
ようするに、開発中、デザイナ画面では有効になるけど、
実行時には無視してほしい属性に対して使うようなものかな。
このXAMLだと、d:XXXXXXやignore:XXXXXXと書かれたものが実行時に無視されそう。
次、これ。
DataContext="{Binding Main, Source={StaticResource Locator}}"
ViewとViewModelの紐付けにDataContextをバインディングしているのは分かる。
[Main]と書かれているのは、MainViewModelのことかな?[ViewModel]部分は省略して書くのか?
問題は、Source={StaticResource Locator}
これは何だ?ViewModelLocatorと関連あるのか?
そう思ってViewModelLocatorのコードを確認したら、以下のコードがあった。
/// <summary> /// Gets the Main property. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "This non-static member is needed for data binding purposes.")] public MainViewModel Main { get { return ServiceLocator.Current.GetInstance<MainViewModel>(); } }
そしてViewModelLocatorのソースの頭に、コメントでこんなことが書いてあった。
/* In App.xaml: <Application.Resources> <vm:ViewModelLocatorTemplate xmlns:vm="clr-namespace:MvvmLightIntroduction.ViewModel" x:Key="Locator" /> </Application.Resources> In the View: DataContext="{Binding Source={StaticResource Locator}, Path=ViewModelName}" */
なるほど、LocatorというキーでアプリケーションのリソースにViewModelを登録していて、
Viewからはリソース経由でViewModelと紐付けるのか。
ん?でもこの使い方の説明にあるような、
DataContext="{Binding Source={StaticResource Locator}, Path=ViewModelName}"
というのはすんなり理解できるけど、
MainWindow.xamlのほうの
DataContext="{Binding Main, Source={StaticResource Locator}}"
という記述はよく分からない。
Bindingの後って順番関係ないんだっけ?Path=って省略できる?
これについてはこの記事が非常に参考になった。
st63jun.hatenablog.jp
時間が無いので今日はここまで。