なぜこれ?
MainWindow.xaml:
<Window x:Class="MVVMProject.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid>
<ContentControl Content="{Binding}"/>
</Grid>
</Window>
ExampleView.xaml を次のように設定します。
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vms="clr-namespace:MVVMProject.ViewModels">
<DataTemplate DataType="{x:Type vms:ExampleVM}" >
<Grid>
<ActualContent/>
</Grid>
</DataTemplate>
</ResourceDictionary>
そして、次のようなウィンドウを作成します。
public partial class App : Application {
protected override void OnStartup(StartupEventArgs e) {
base.OnStartup(e);
MainWindow app = new MainWindow();
ExampleVM context = new ExampleVM();
app.DataContext = context;
app.Show();
}
}
いつこんなことができるの?
App.xaml: (起動ウィンドウ/ビューを設定)
<Application x:Class="MVVMProject.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="ExampleView.xaml">
</Application>
ExampleView.xaml: (ResourceDictionary ではなく Window)
<Window x:Class="MVVMProject.ExampleView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vms="clr-namespace:MVVMProject.ViewModels">
>
<Window.DataContext>
<vms:ExampleVM />
</Window.DataContext>
<Grid>
<ActualContent/>
</Grid>
</Window>
基本的には、「View as DataTemplate」(VaD) と「View as Window」(VaW) です。
比較についての私の理解は次のとおりです。
- VaD: ウィンドウを閉じずにビューを切り替えることができます。(これは私のプロジェクトには望ましくありません)
- VaD: VM はビューについてまったく何も知りませんが、VaW では、別のウィンドウを開くときに (のみ) インスタンス化できなければなりません。
- VaW: デザイナーでレンダリングされた xaml を実際に見ることができます (少なくとも現在のセットアップでは、VaD を使用することはできません)。
- VaW: ウィンドウの開閉を直感的に操作できます。各ウィンドウには、対応するビュー (およびビューモデル) があります。
- VaD: ViewModel は、プロパティを介して初期ウィンドウの幅、高さ、サイズ変更可能性などを渡すことができます (VaW では、ウィンドウに直接設定されます)。
- VaW: FocusManager.FocusedElement を設定できます (VaD での方法がわからない)
- VaW: ウィンドウ タイプ (リボン、ダイアログなど) がビューに組み込まれているため、ファイルが少なくなります。
それで、ここで何が起こっているのですか?Windows を XAML で構築し、VM のプロパティを介してデータにクリーンにアクセスし、それで作業を完了することはできませんか? コード ビハインドは同じです (実質的にゼロ)。
すべての View のものを ResourceDictionary にシャッフルする必要がある理由を理解するのに苦労しています。