2017-03-08 17 views
2

私は銀色のプロジェクトを持っています。 App.xamlでは、我々はViewModelを適切な場所に配置してください

<Application.Resources> 
    <ResourceDictionary> 
     <ResourceDictionary.MergedDictionaries> 
      <ResourceDictionary Source="Assets/Styles.xaml"/> 
     </ResourceDictionary.MergedDictionaries> 
    </ResourceDictionary> 
</Application.Resources> 

はその後Assets/Styles.xamlに、我々はViewModelにしていています。

<ResourceDictionary 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data" 
xmlns:local="clr-namespace:MyWeb.MyProj" 
xmlns:sys="clr-namespace:System;assembly=mscorlib" 
xmlns:localViewModels="clr-namespace:MyWeb.MyProj.ViewModels"> 

<ResourceDictionary.MergedDictionaries> 

</ResourceDictionary.MergedDictionaries> 

<localViewModels:MyProjViewModel x:Key="ViewModel" /> 
... 
<telerikGridView:RadGridView 
    ... 
    ItemsSource="{Binding Schedules}" 
    SelectedItem="{Binding SelectedWeek, Mode=TwoWay, Source={StaticResource ViewModel}}"> 

private MyProjViewModel viewModel; 

public MyProjViewModel ViewModel 
{ 
    get 
    { 
     if (this.viewModel == null) 
     { 
      this.viewModel = new MyProjViewModel(); 
     } 
     return this.viewModel; 
    } 
    set 
    { 
     if (this.viewModel != value) 
     { 
      this.viewModel = value; 
     } 
    } 
} 

次にコンストラクタで、私たちは

public MainPage() 
{ 
    InitializeComponent(); 
    this.DataContext = this.ViewModel; 
    this.ViewModel = this.DataContext as MyProj; 

としてのViewModelを使用最後にMainPage.xaml.csで、我々が持っている、それは動作しますが、私はわからないが、 ViewModelがStyles.xamlに配置されているため、ViewModelを使用するのに最適な構造です。そうでない場合、それを修正する方法は?

+1

私は、スタイルからViewModel定義を削除します。それをMainPageコンストラクタに入れます。 –

答えて

0

アプリケーションのライフサイクル全体でViewModelの特定のインスタンスを使用できるようにするには、リソースディクショナリで定義することができます(もちろん、リソースディクショナリからリソースを参照する必要があります)あなたの質問のように使用しないでください)。

より良い解決策は、(style.xamlの定義なしで)ビューのコンストラクタでそれを作成することです。

public MyProjectViewModel ViewModel { get; set; } 

public MainPage() 
{ 
    InitializeComponent(); 
    this.ViewModel = new MyProjViewModel(); 
    this.DataContext = this.ViewModel; 
} 
関連する問題