在本文中將演示如何在Windows 8進行MVVM開發,首先我們准備兩個輔助類如下:
ViewModeBase類 :
public class ViewModeBase : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// 屬性變化時觸發事件 /// </summary> /// <param name="propertyName"></param> protected void OnPropertyChanged( string propertyName ) { var handler = this.PropertyChanged; if ( handler != null ) { handler( this, new PropertyChangedEventArgs( propertyName ) ); } } }
DelegateCommand類:
public class DelegateCommand : ICommand { private readonly Action m_exeAction; private readonly Func<bool> m_canExeAction; /// <summary> /// 構造函數 /// </summary> /// <param name="executeAction"></param> /// <param name="canExecuteAction"></param> public DelegateCommand(Action executeAction, Func<bool> canExecuteAction) { m_exeAction = executeAction; m_canExeAction = canExecuteAction; } /// <summary> /// 構造函數 /// </summary> /// <param name="executeAction"></param> /// <param name="canExecuteAction"></param> public DelegateCommand(Action executeAction) : this(executeAction, null) { } /// <summary> /// 判斷是否執行操作 /// </summary> /// <param name="parameter"></param> /// <returns></returns> public bool CanExecute(object parameter) { if (m_canExeAction != null) { return m_canExeAction(); } return true; } /// <summary> /// 是否執行操作的變更發生時 /// </summary> public event EventHandler CanExecuteChanged; /// <summary> /// 執行操作的內容,可以變為Action行為 /// </summary> /// <param name="parameter"></param> public void Execute(object parameter) { if (CanExecute(parameter)) { m_exeAction(); } } protected void OnCanExecuteChanged(object sender, EventArgs args) { var handler = CanExecuteChanged; if ( handler != null ) { handler( this, EventArgs.Empty ); } } public void RaiseCanExecuteChanged() { OnCanExecuteChanged(this, EventArgs.Empty); } }
Model層如下:
/// <summary> /// 圖片Model /// </summary> public class BookModel : ViewModeBase { private string txtTitle; private string txtContent; private string imageUrl; private bool isSelect; /// <summary> /// 標題 /// </summary> public string TxtTitle { get { return txtTitle; } set { txtTitle = value; OnPropertyChanged("TxtTitle"); } } /// <summary> /// 內容 /// </summary> public string TxtContent { get { return txtContent; } set { txtContent = value; OnPropertyChanged("TxtContent"); } } /// <summary> /// 圖片URL地址 /// </summary> public string ImageUrl { get { return imageUrl; } set { imageUrl = value; OnPropertyChanged("ImageUrl"); } } }
ViewModel層代碼如下:
public class MainPageViewModel:ViewModeBase { private ICommand getTextCommand; private ICommand btnCommand; private string showText; private string getText; ObservableCollection<BookModel> books = new ObservableCollection<BookModel> (){ new BookModel(){ TxtTitle="盤龍",TxtContent="大小的血睛鬃毛獅,力大無窮 的紫睛金毛猿,毀天滅地的九頭蛇皇,攜帶著毀滅雷電的恐怖雷龍這裡無奇不有,這是一個廣博的魔幻世界。 ", ImageUrl="http://image.qidian.com/books/1017141/1017141.jpg" }, new BookModel(){ TxtTitle="縱橫輪回",TxtContent="李沐然,本為身懷諸子百 家所長的大神通者,在收取世間最後一顆神雷珠之時和神雷珠一道重生異世神雷之力,刑罰天下", ImageUrl="http://image.qidian.com/books/1.jpg" }, new BookModel(){ TxtTitle="巫師世界",TxtContent="穿越到異世界成為普通的 小家族子弟,帶著具有分析能力的生物芯片開始強大之旅..... ", ImageUrl="http://image.qidian.com/books/2443169/2443169.jpg" }, new BookModel(){ TxtTitle="殺神",TxtContent="在這個人吃人的瘋狂世界,神 已無力回天,就讓我踏著漫天諸神的累累屍骨來普渡這芸芸眾生……", ImageUrl="http://image.qidian.com/books/1911245/1911245.jpg" } }; public ICommand GetTextCommand { get { return getTextCommand; } set { getTextCommand = value; } } public ICommand BtnCommand { get { return btnCommand; } set { btnCommand = value; } } public string ShowText { get { return showText; } set { showText = value; OnPropertyChanged("ShowText"); } } public string GetText { get { return getText; } set { getText = value; OnPropertyChanged("GetText"); } } public MainPageViewModel() { BtnCommand = new DelegateCommand(Btn_Executed); GetTextCommand = new DelegateCommand(GetText_Executed); } private void GetText_Executed() { GetText = "'" + ShowText + "'是我獲取到的值"; } private void Btn_Executed() { ShowText = "您已經點擊了按鈕,請在這裡輸入值"; } public ObservableCollection<BookModel> Books { get { return books; } } }
最後View層代碼如下:
<Page.DataContext> <local:MainPageViewModel /> </Page.DataContext> <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}"> <Button Command="{Binding BtnCommand}" Content="點擊我" Padding="8" Margin="72,138,0,494" Height="60" Width="100" Grid.Row="0"/> <TextBox Name="tbshow" Height="60" Text="{Binding ShowText,Mode=TwoWay}" Margin="230,176,744,532"/> <GridView x:Name="mainGridView" ItemsSource="{Binding Books}" VerticalAlignment="Center" Grid.Row="1"> <GridView.ItemsPanel> <ItemsPanelTemplate> <StackPanel Orientation="Horizontal" /> </ItemsPanelTemplate> </GridView.ItemsPanel> <GridView.ItemTemplate> <DataTemplate> <Grid Width="250" Height="200" Background="#33CCCCCC"> <Grid.ColumnDefinitions> <ColumnDefinition Width="110"></ColumnDefinition> <ColumnDefinition></ColumnDefinition> </Grid.ColumnDefinitions> <Image Grid.Column="0" Margin="5,0,0,0" Source="{Binding ImageUrl}" Stretch="None"></Image> <TextBlock Grid.Column="1" Margin="15,15,0,0" Foreground="White" Text="{Binding TxtTitle}" FontWeight="Bold" FontSize="18" TextWrapping="Wrap"/> <TextBlock Grid.Column="1" Margin="15,40,0,0" Foreground="White" Text="{Binding TxtContent}" FontWeight="Light" FontSize="13" TextWrapping="Wrap"/> </Grid> </DataTemplate> </GridView.ItemTemplate> </GridView> <Button Command="{Binding GetTextCommand}" Content="點擊我獲取值" Padding="8" Margin="667,176,0,532" Height="60" Width="123" Grid.Row="0"/> <TextBlock HorizontalAlignment="Left" Margin="795,198,0,0" TextWrapping="Wrap" Text="{Binding GetText,Mode=TwoWay}" VerticalAlignment="Top" Height="22" Width="379"/> </Grid> </Page>
這樣我們就可以將前台和後台代碼分層編寫,一邊UI和後台開發人員同時進行開發任 務。當然這是最簡單的MVVM開發框架,實際開發中我們還需要完善各種事件的輔助類和其他相關輔助方法才能 形成一個完整的MVVM框架。當然也可以使用網上的一些現成框架如MVVMLight等。
下面我們看本文的示例圖片,如需源碼請下載: http://files.cnblogs.com/chengxingliang/Win8MVVM.rar