2013-09-26 61 views
1

我是MVVM和WPF的新手,試圖在WPF和MVVM中使用ICommand。以下是代碼。ICommand與WPF中的MVVM

有人可以幫助知道爲什麼下面的代碼不工作,意味着按鈕點擊沒有任何反應。

感謝您的幫助。

查看

<Grid> 
<Button Height="40" Width="200" Name="button1" Command="{Binding Path=Click}" >Click Me</Button> 
    </Grid> 

App.xaml.cs

public partial class App : Application 
    { 
     protected override void OnStartup(StartupEventArgs e) 
     { 
      base.OnStartup(e); 
      MainWindow mainWindow = new MainWindow(); 
      MainWindowViewModel vm = new MainWindowViewModel(); 
      mainWindow.DataContext = vm; 

     } 

    } 

MainWindowViewModel.cs

namespace TestWPFApplication.ViewModel 
{ 
    public class MainWindowViewModel 
    { 
     private ICommand _click; 
     public ICommand Click 
     { 
      get 
      { 
       if (_click == null) 
        _click = new CommandTest(); 
       return _click; 
      } 
      set 
      { _click = value; } 
     } 

     private class CommandTest : ICommand 
     { 

      public bool CanExecute(object parameter) 
      { 
       return true; 
      } 

      public event EventHandler CanExecuteChanged; 

      public void Execute(object parameter) 
      { 
       MessageBox.Show("Hi! Test"); 
      } 

     } 
    }    
} 
+0

http://stackoverflow.com/questions/1468791/wpf-icommand-mvvm-implementation –

回答

4

它看起來像你的OnStartup方法正在實例化一個MainWindow並從不顯示它。您可能已在中設置了XAML,該數據創建的數據上下文未設置爲MainWindow

您可以刪除StartupUri並致電mainWindow.Show()。或者,您可以擺脫OnStartup方法並在主窗口的構造函數中設置數據上下文。

+0

很好..謝謝..現在工作... :) – Saroj

0

您不需要在OnStartup中初始化此Window

MainWindow構造函數Initialize之後創建ViewModel的實例,它應該工作。