Start the visual studio and
create a WPF application.
Make a ViewModelBase
class and inherite the InotifyPropertyChanged interface.
Create a new method in “ViewModelBase”
class for show the message like -
public void MessageBoxShow(string message)
{
MessageBox.Show(message, "",
MessageBoxButton.OK, MessageBoxImage.Error);
}
After create a Helper class in helper folder name
is BaseCommand and Inharite/implement the Icommand Interface.
Like-
internal class BaseCommand : ICommand
{
private readonly
Action _command;
private readonly Func<bool>
_canExecute;
public BaseCommand(Action
command, Func<bool>
canExecute = null)
{
if (command == null)
throw new
ArgumentNullException("command");
_canExecute = canExecute;
_command = command;
}
public void Execute(object parameter)
{
_command();
}
public bool
CanExecute(object parameter)
{
if (_canExecute == null)
return true;
return _canExecute();
}
public event EventHandler CanExecuteChanged;
}
After create a class (EmployeViewModel) in ViewModel folder and inherite the “ViewModelBase” class
and add namespace the Basecommand class.
Like-
using WPF_MVVM_MessageBox.Helper;
Create a private method in “EmployeViewModel” class for save
the data and call the MessageBoxShow method.
private void Save()
{
//here code for Save the Data
MessageBoxShow("Data Save Successfully.");
}
Create a Icommand type property in “EmployeViewModel” class and
add the Save method for Execute
Like-
public ICommand
ClickCommand { get { return
new BaseCommand(Save);
} }
Finally add the reference of ViewModel directory in
XAML window.
Like-
xmlns:me="clr-namespace:WPF_MVVM_MessageBox.ViewModels" Title="Create Employee" Height="400" Width="400"
After create a Window resource in XAML file.
Like-
<Window.Resources>
<me:EmployeeViewModel x:Key="viewModel"
/>
</Window.Resources>
Add a button in XAML file.
Like-
<Button Height="50" Width="100" Content="Click
Me" Name="btnnew" Command="{Binding Source={StaticResource viewModel}, Path= ClickCommand}"
/>
and bind the button command to “ClickCommand”
property.
Finally Run the Application and click on button
cheer.
No comments:
Post a Comment