Reputation: 217
I am new to MVVM and WPF, trying to use ICommand in WPF and MVVM. Below is the code.
Can someone please help to know why the below code is not working, means nothing happens on button click.
Appreciate your help.
View
<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");
}
}
}
}
Upvotes: 1
Views: 489
Reputation: 427
You don't need to initialize this Window
in OnStartup
.
In MainWindow
constructor after Initialize
create instance of ViewModel
and it should work.
Upvotes: 0
Reputation: 6113
It looks like your OnStartup
method is instantiating a MainWindow
and never showing it. You probably have the StartupUri
set in XAML which is creating a different MainWindow
with the data context not set.
You could remove the StartupUri
and call mainWindow.Show()
. Alternatively, you could get rid of the OnStartup
method and set up the data context in the main window's constructor.
Upvotes: 4