close

image


   1: <Window x:Class="WpfApp3.MainWindow"
   2:         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   3:         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   4:         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
   5:         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
   6:         xmlns:local="clr-namespace:WpfApp3"
   7:         mc:Ignorable="d"
   8:         Title="MainWindow" Height="450" Width="800">
   9:     <Grid>
  10:         <Button Height="60"
  11:                 Width="200"
  12:                 Click="MyButton_Click"
  13:                 Content="點我"/>
  14:  
  15:     </Grid>
  16: </Window>

傳統習慣上,會寫呼叫一個 Callback函式(MyButton_Click)

image


   1: private void MyButton_Click(object sender, RoutedEventArgs e)
   2: {
   3:     MessageBox.Show("點我!");
   4: }

現在,改用MVVM方式來進行上述工作

image

先新增一個ShowCommand類別並加入下列兩組命名空間

   1: using System.Windows;
   2: using System.Windows.Input;

ShowCommand繼承ICommand

滑鼠移至紅色底線提示,選擇”顯示可能的修正

image

選擇”實作介面

image

ShowCommand類別繼承ICommand

   1: public class ShowCommand : ICommand
   2: {
   3:     public event EventHandler CanExecuteChanged;
   4:  
   5:     public bool CanExecute(object parameter)
   6:     {
   7:         return true;
   8:     }
   9:  
  10:     public void Execute(object parameter)
  11:     {
  12:         MessageBox.Show(parameter.ToString());
  13:     }
  14: }

接著新增一個MainViewModel類別並加入下列兩組命名空間

   1: using System.Windows;
   2: using System.Windows.Input;

image


   1: using System.Windows;
   2: using System.Windows.Input;
   3: namespace WpfApp3
   4: {
   5:     public class MainViewModel
   6:     {
   7:         ICommand showCommand = new ShowCommand();
   8:         public ICommand Show
   9:         {
  10:             get { return showCommand; }
  11:         }       
  12:     }
  13: }

修改xml,加入資料上下文(DataContext)

   1: <Window.DataContext >
   2:     <local:MainViewModel />
   3: </Window.DataContext>

移除Click事件,並新增Command屬性

image

跳出Command欄位


image

點選Command欄位右邊的黃色點,選擇”建立資料連結”

image

選擇MainViewModel.Show()

image

設定完成

image

加入命令參數CommandParameter

   1: <Window.DataContext >
   2:     <local:MainViewModel />
   3: </Window.DataContext>
   4: <Grid>
   5:     <Button Height="60"
   6:             Width="200"
   7:             Command="{Binding Show, Mode=OneWay}"
   8:             CommandParameter="點擊我"
   9:             Content="點我"/>
  10: </Grid>

防止傳遞Null參數,所以修改一下ShowCommand類別

   1: public class ShowCommand : ICommand
   2:   {
   3:       public event EventHandler CanExecuteChanged;
   4:  
   5:       public bool CanExecute(object parameter)
   6:       {
   7:           return true;
   8:       }
   9:  
  10:       public void Execute(object parameter)
  11:       {
  12:           if( parameter!=null)
  13:           MessageBox.Show(parameter.ToString());
  14:       }
  15:   }

image

arrow
arrow
    全站熱搜

    me1237guy 發表在 痞客邦 留言(0) 人氣()