上一篇文章介紹了怎樣快速搭建一個基於MVVMLight的程序http://www.cnblogs.com/whosedream/p/mvvmlight1.html算是簡單入門了下,今天咱們來作一個稍許複雜點的應用,關於這個應用我是找了個CodePlex上的小例子加以改造的。html
需求大體以下app
1.用戶輸入必定規格的數據mvvm
例如:ide
2.用戶自定義類別,並將索引值(指用於匹配數據的關鍵字)關聯上類別this
例如:spa
3.程序根據類別以及它所關聯的索引,生成餅狀圖。設計
具體的邏輯咱們就不去分析了,這裏咱們是要用MVVM思想去開發,固然還得是基於MVVMLight的。code
首先不管如何,咱們會設計一個主頁面,而後1,2,3功能各一個頁面嵌入到主頁面中去,這裏咱們就用tab標籤進行控制頁面切換,假設咱們的View已經設計好了component
每個View確定都會有一個ViewModel,而且一個ViewModel可能會包含其它的ViewModel,咱們要開發的ViewModel也會是這麼個結構,以下圖htm
主頁面綁定了一個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承載數據。
上一張效果圖
源碼下載 若是以爲有幫助就頂一個吧,讓我樂呵樂呵