2017-03-08 78 views
2

我有一個Silverlight項目。在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}}"> 

最後在MainPage.xaml.cs中,我們有

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的最佳結構,因爲它放置在Styles.xaml中。如果沒有,如何糾正?

+1

我會從樣式中刪除ViewModel定義。把它放在MainPage構造函數中。 –

回答

0

如果您希望ViewModel的一個特定實例可用於整個應用程序的生命週期,您可以像Resource一樣在Resource Dictionary中定義它(當然,您必須從資源字典中引用它而不是像你在你的問題中那樣使用)。

更好的解決方案是在視圖的構造函數中創建它(沒有styles.xaml中的定義)。

public MyProjectViewModel ViewModel { get; set; } 

public MainPage() 
{ 
    InitializeComponent(); 
    this.ViewModel = new MyProjViewModel(); 
    this.DataContext = this.ViewModel; 
}