Hi,
you can use CommandParameter binded to DataContext (=MyViewModel). Try following demo with yours code:
XAML MainWindow:
<Window x:Class="WpfApp2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp2"
xmlns:vm="clr-namespace:WpfApp2.ViewModel"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="211">
<Window.DataContext>
<vm:MyViewModel/>
</Window.DataContext>
<Window.Resources>
<Style TargetType="Label">
<Setter Property="Margin" Value="5"/>
</Style>
<Style TargetType="TextBox">
<Setter Property="Margin" Value="5"/>
</Style>
<Style TargetType="Button">
<Setter Property="Margin" Value="5"/>
</Style>
</Window.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Label Grid.Row="0" Grid.Column="0" Content="Name:"/>
<TextBox Grid.Row="0" Grid.Column="1" Text="{Binding nameText}"/>
<Label Grid.Row="1" Grid.Column="0" Content="Age:"/>
<TextBox Grid.Row="1" Grid.Column="1" Text="{Binding ageText}"/>
<Button Grid.Row="2" Grid.Column="1" Content="Birthday"
Command="{Binding DisplayBirthdayCommand}" CommandParameter="{Binding}"/>
</Grid>
</Window>
MyCommand:
using System;
using System.Windows.Input;
namespace WpfApp2.ViewModel
{
public class MyCommand : ICommand
{
public event EventHandler CanExecuteChanged;
private Action<object> _execute;
public MyCommand(Action<object> execute) => _execute = execute;
public bool CanExecute(object parameter) => true;
public void Execute(object parameter) => _execute.Invoke(parameter);
}
}
MyViewModel:
using System;
using System.Windows;
namespace WpfApp2.ViewModel
{
public class MyViewModel
{
public string nameText { get; set; }
public string ageText { get; set; }
public MyCommand DisplayBirthdayCommand { get; private set; }
public MyViewModel()
{
DisplayBirthdayCommand = new MyCommand(DisplayBirthday);
}
private void DisplayBirthday(object state)
{
MyViewModel vm = state as MyViewModel;
MessageBox.Show(string.Format("Happy Birthday, {0}! Age: {1}", vm.nameText, Convert.ToInt32(vm.ageText) + 1), $"{vm.nameText}'s Birthday");
}
}
}