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中。如果沒有,如何糾正?
我會從樣式中刪除ViewModel定義。把它放在MainPage構造函數中。 –