上一篇文章介紹了怎樣快速搭建一個基于MVVMLight的程式http://www.cnblogs.com/whosedream/p/mvvmlight1.html算是簡單入門了下,今天我們來做一個稍許複雜點的應用,關于這個應用我是找了個CodePlex上的小例子加以改造的。
需求大緻如下
1.使用者輸入一定規格的資料
例如:
- buy car;100000
- buy bike;3000
- receive;20000
2.使用者自定義類别,并将索引值(指用于比對資料的關鍵字)關聯上類别
例如:
- category name: 買車 ,token value:car
- category name: 買自行車,token value: bike
- category name: 收入,token value: receive
3.程式根據類别以及它所關聯的索引,生成餅狀圖。
具體的邏輯我們就不去分析了,這裡我們是要用MVVM思想去開發,當然還得是基于MVVMLight的。
首先無論如何,我們會設計一個首頁面,然後1,2,3功能各一個頁面嵌入到首頁面中去,這裡我們就用tab标簽進行控制頁面切換,假設我們的View已經設計好了

每一個View肯定都會有一個ViewModel,并且一個ViewModel可能會包含其它的ViewModel,我們要開發的ViewModel也會是這麼個結構,如下圖
首頁面綁定了一個MainViewModel,而MainViewModel還包含了三個ViewModel,分别用來綁定對應的Tab标簽頁面,category1,category2之類也就是Model
App.xaml
<Application.Resources>
<vm:ViewModelLocator x:Key="Locator"
d:IsDataSource="True" />
</Application.Resources>
App的資源檔案照例添加ViewModelLocator資源,用來實作IOC功能
ViewModelLocator代碼
/// <summary>
/// Initializes a new instance of the ViewModelLocator class.
/// </summary>
public ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
SimpleIoc.Default.Register<MainViewModel>();
}
/// <summary>
/// 主界面ViewModel包含了3個子ViewModel
/// </summary>
public MainViewModel Main
{
get
{
return ServiceLocator.Current.GetInstance<MainViewModel>();
}
}
關于指令綁定,看一段稍許複雜點的listbox的指令綁定
<ListBox x:Name="CategoryListbox"
Margin="0,28,15,0"
ItemsSource="{Binding Categories}"
SelectedItem="{Binding SelectedCategory, Mode=TwoWay}" >
<ListBox.ItemTemplate>
<DataTemplate >
<StackPanel Orientation="Horizontal">
<TextBlock TextWrapping="Wrap" Text="{Binding Name}" Margin="2,0" VerticalAlignment="Center" MinWidth="100"/>
<Button>
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<GalaSoft_MvvmLight_Command:EventToCommand Command="{Binding RemoveCommand}" />
</i:EventTrigger>
</i:Interaction.Triggers>
<Image Height="16" Source="/BankCharts.Silverlight;component/Media/Pictures/Remove.png" Stretch="Fill" Width="16"/>
</Button>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
對應下圖
要實作點選X删除項
我們看到Command綁定的是RemoveCommand,來看看背景如何實作的
//清單項上删除類别指令
public RelayCommand RemoveCommand { get; set; }
public void PrepareCommand()
{
RemoveCommand = new RelayCommand(Remove);
}
public void Remove()
{
//容器中移除目前項
_parent.RemoveCategory(this);
}
定義了一個RelayCommand,它是何方神聖?
public class RelayCommand : ICommand
知道了嗎,它是MVVMLight的對ICommand的一層包裝
想了想代碼太多,一一貼出未免嫌啰嗦,那就總結下
View關聯上ViewModel,CRUD業務邏輯寫在ViewModel中,ViewModel操作Model,Model承載資料。
上一張效果圖
源碼下載下傳 如果覺得有幫助就頂一個吧,讓我樂呵樂呵
time waits for no one
如果,您認為閱讀這篇部落格讓您有些收獲,不妨點選一下右下角的 【
推薦】 按鈕。
因為,我的寫作熱情離不開您的肯定支援。
感謝您的閱讀,如果您對我的部落格所講述的内容有興趣,請繼續關注我的後續部落格。