简单的MVVM视频、源码(带“事件”处理)

视频、源码作者刘铁锰老师,博客 :http://www.cnblogs.com/prism/

源代码有改动,增加了事件处理。

MainWindow.xaml :

View Code
复制代码
 1 <Window x:Class="CrazyElephant.MainWindow"
 2         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 3         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 4         xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
 5         xmlns:local="clr-namespace:CrazyElephant.Commands"
 6        Title="{Binding Restaurant.Name, StringFormat=\{0\}-在线订餐}" Height="600" Width="1000"
 7         WindowStartupLocation="CenterScreen">
 8     <Border BorderBrush="Orange" BorderThickness="3" CornerRadius="6" Background="Yellow">
 9         <Grid x:Name="Root" Margin="4">
10             <Grid.RowDefinitions>
11                 <RowDefinition Height="Auto" />
12                 <RowDefinition Height="*" />
13                 <RowDefinition Height="Auto" />
14             </Grid.RowDefinitions>
15             <Border BorderBrush="Orange" BorderThickness="1" CornerRadius="6" Padding="4">
16                 <StackPanel>
17                     <StackPanel Orientation="Horizontal">
18                         <StackPanel.Effect>
19                             <DropShadowEffect Color="LightGray" />
20                         </StackPanel.Effect>
21                         <TextBlock Text="欢迎光临-" FontSize="60" FontFamily="LiShu" />
22                         <TextBlock Text="{Binding Restaurant.Name}" FontSize="60" FontFamily="LiShu" />
23                     </StackPanel>
24                     <StackPanel Orientation="Horizontal">
25                         <TextBlock Text="小店地址:" FontSize="24" FontFamily="LiShu" />
26                         <TextBlock Text="{Binding Restaurant.Address}" FontSize="24" FontFamily="LiShu" />
27                     </StackPanel>
28                     <StackPanel Orientation="Horizontal">
29                         <TextBlock Text="订餐电话:" FontSize="24" FontFamily="LiShu" />
30                         <TextBlock Text="{Binding Restaurant.PhoneNumber}" FontSize="24" FontFamily="LiShu" />
31                     </StackPanel>
32                 </StackPanel>
33             </Border>
34             <DataGrid AutoGenerateColumns="False" GridLinesVisibility="None" CanUserDeleteRows="True"
35                     CanUserAddRows="False" Margin="0,4" Grid.Row="1" FontSize="16" ItemsSource="{Binding DishMenu,Mode=TwoWay}">
36                 <DataGrid.Columns>
37                     <DataGridTextColumn Header="菜品" Binding="{Binding Dish.Name}" Width="120" />
38                     <DataGridTextColumn Header="种类" Binding="{Binding Dish.Category}" Width="120" />
39                     <DataGridTextColumn Header="点评" Binding="{Binding Dish.Comment}" Width="120" />
40                     <DataGridTextColumn Header="推荐分数" Binding="{Binding Dish.Score}" Width="120" />
41 
42                     <DataGridTemplateColumn Header="选择" SortMemberPath="IsSelected" Width="120">
43                         <DataGridTemplateColumn.CellTemplate>
44                             <DataTemplate>
45                                 <CheckBox IsChecked="{Binding IsSelected,UpdateSourceTrigger=PropertyChanged}" Command="{Binding DataContext.SelectMenuItemCommand,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type DataGrid}}}"/>
46                             </DataTemplate>
47                         </DataGridTemplateColumn.CellTemplate>
48                     </DataGridTemplateColumn>
49                     <DataGridTemplateColumn Header="删除" Width="120">
50                         <DataGridTemplateColumn.CellTemplate>
51                             <DataTemplate>
52                                 <Button Content="删除">
53                                     <i:Interaction.Triggers>
54                                         <i:EventTrigger EventName="Click">
55                                             <local:ExtendedInvokeCommandAction Command="{Binding DataContext.DeleteMenuItemCommand,Mode=OneWay,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type DataGrid}}}" CommandParameter="{Binding}"/>
56                                         </i:EventTrigger>
57                                     </i:Interaction.Triggers>
58                                 </Button>
59                             </DataTemplate>
60                         </DataGridTemplateColumn.CellTemplate>
61                     </DataGridTemplateColumn>
62                 </DataGrid.Columns>
63             </DataGrid>
64             <StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Grid.Row="2">
65                 <TextBlock Text="共计" VerticalAlignment="Center" />
66                 <TextBox IsReadOnly="True" TextAlignment="Center" Width="120" Text="{Binding Count}" Margin="4,0" />
67                 <Button Content="Order" Height="24" Width="120" Command="{Binding PlaceOrderCommand}" />
68             </StackPanel>
69         </Grid>
70     </Border>
71 </Window>
复制代码

MainWindowViewModel.cs :

View Code
复制代码
  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 using Microsoft.Practices.Prism.Commands;
  6 using Microsoft.Practices.Prism.ViewModel;
  7 using CrazyElephant.Models;
  8 using CrazyElephant.Services;
  9 using System.Windows;
 10 using System.Windows.Input;
 11 using CrazyElephant.Commands;
 12 using System.Collections.ObjectModel;
 13 using Microsoft.Expression.Interactivity.Core;
 14 
 15 namespace CrazyElephant.ViewModels
 16 {
 17     public class MainWindowViewModel : NotificationObject
 18     {
 19         public ActionCommand DeleteMenuItemCommand { get; set; }
 20         public DelegateCommand PlaceOrderCommand { get; set; }
 21         public DelegateCommand SelectMenuItemCommand { get; set; }
 22        
 23         private int count;
 24 
 25         public int Count
 26         {
 27             get { return count; }
 28             set
 29             {
 30                 count = value;
 31                 this.RaisePropertyChanged("Count");
 32             }
 33         }
 34 
 35         private Restaurant restaurant;
 36 
 37         public Restaurant Restaurant
 38         {
 39             get { return restaurant; }
 40             set
 41             {
 42                 restaurant = value;
 43                 this.RaisePropertyChanged("Restaurant");
 44             }
 45         }
 46 
 47         private ObservableCollection<DishMenuItemViewModel> dishMenu;
 48 
 49         public ObservableCollection<DishMenuItemViewModel> DishMenu
 50         {
 51             get { return dishMenu; }
 52             set
 53             {
 54                 dishMenu = value;
 55                 this.RaisePropertyChanged("DishMenu");
 56             }
 57         }
 58 
 59         public void LoadRestaurant()
 60         {
 61             this.Restaurant = new Restaurant
 62             {
 63                 Name = "Crazy大象",
 64                 Address = "北京市海淀区万泉河路紫金庄园1号楼 1层 113室(亲们:这地儿特难找!)",
 65                 PhoneNumber = "15210365423 or 82650336"
 66             };
 67         }
 68 
 69         public void LoadDishMenu()
 70         {
 71             IDataService ds = new XmlDataService();
 72             var dishes = ds.GetAllDishes();
 73             this.DishMenu = new ObservableCollection<DishMenuItemViewModel>();
 74             foreach (var dish in dishes)
 75             {
 76                 this.DishMenu.Add(new DishMenuItemViewModel { Dish = dish });
 77             }
 78         }
 79 
 80         public MainWindowViewModel()
 81         {
 82             this.LoadRestaurant();
 83             this.LoadDishMenu();
 84             this.SelectMenuItemCommand = new DelegateCommand(this.SelectMenuItemExecute);
 85             this.PlaceOrderCommand = new DelegateCommand(this.PlaceOrderCommandExecute);
 86             this.DeleteMenuItemCommand = new ActionCommand(this.DelelteMenuItemExecute);
 87         }
 88 
 89         public void SelectMenuItemExecute()
 90         {
 91             this.Count = this.DishMenu.Count(c => c.IsSelected == true);
 92         }
 93 
 94         public void PlaceOrderCommandExecute()
 95         {
 96             var selectedDishes = this.DishMenu.Where(i => i.IsSelected == true).Select(i => i.Dish.Name).ToList();
 97             IOrderService orderService = new MockOrderService();
 98             orderService.PlaceOrder(selectedDishes);
 99             MessageBox.Show("订餐成功!");
100         }
101 
102         public void DelelteMenuItemExecute(object obj)
103         {
104             ExtendedCommandParameter para = obj as ExtendedCommandParameter;
105             DishMenuItemViewModel dm = para.Parameter as DishMenuItemViewModel;
106             this.DishMenu.Remove(dm);
107             MessageBox.Show("删除成功!");
108         }
109 
110     }
111 }
复制代码

ExtendedInvokeCommandAction.cs :

View Code
复制代码
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Windows;
 6 using System.Windows.Input;
 7 using System.Windows.Interactivity;
 8 
 9 namespace CrazyElephant.Commands
10 {
11     public class ExtendedInvokeCommandAction : TriggerAction<FrameworkElement>
12     {
13         public static readonly DependencyProperty CommandProperty = DependencyProperty.Register("Command", typeof(ICommand), typeof(ExtendedInvokeCommandAction), new PropertyMetadata(null, CommandChangedCallback));
14         public static readonly DependencyProperty CommandParameterProperty = DependencyProperty.Register("CommandParameter", typeof(object), typeof(ExtendedInvokeCommandAction), new PropertyMetadata(null, CommandParameterChangedCallback));
15 
16         private static void CommandParameterChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
17         {
18             var invokeCommand = d as ExtendedInvokeCommandAction;
19             if (invokeCommand != null)
20                 invokeCommand.SetValue(CommandParameterProperty, e.NewValue);
21         }
22 
23         private static void CommandChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
24         {
25             var invokeCommand = d as ExtendedInvokeCommandAction;
26             if (invokeCommand != null)
27                 invokeCommand.SetValue(CommandProperty, e.NewValue);
28         }
29 
30         protected override void Invoke(object parameter)
31         {
32             if (this.Command == null)
33                 return;
34 
35             if (this.Command.CanExecute(parameter))
36             {
37                 var commandParameter = new ExtendedCommandParameter(parameter as EventArgs, this.AssociatedObject,
38                                                                     GetValue(CommandParameterProperty));
39                 this.Command.Execute(commandParameter);
40             }
41         }
42 
43         #region public properties
44 
45         public object CommandParameter
46         {
47             get { return GetValue(CommandParameterProperty); }
48             set { SetValue(CommandParameterProperty, value); }
49         }
50 
51         public ICommand Command
52         {
53             get { return GetValue(CommandProperty) as ICommand; }
54             set { SetValue(CommandParameterProperty, value); }
55         }
56 
57         #endregion
58     }
59 }
复制代码

ExtendedCommandParameter.cs :

View Code
复制代码
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Windows;
 6 
 7 namespace CrazyElephant.Commands
 8 {
 9     public class ExtendedCommandParameter
10     {
11         public ExtendedCommandParameter(EventArgs eventArgs, FrameworkElement sender, object parameter)
12         {
13             EventArgs = eventArgs;
14             Sender = sender;
15             Parameter = parameter;
16         }
17 
18         public EventArgs EventArgs { get; private set; }
19         public FrameworkElement Sender { get; private set; }
20         public object Parameter { get; private set; }
21     }
22 }
复制代码
 

原文地址:http://www.cnblogs.com/ynbt/archive/2013/03/24/2979964.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值