I make a demo to implement the data in ViewModel like below:
Xaml code is:
<Window.Resources>
<HierarchicalDataTemplate DataType="{x:Type local:UserModel}">
<MenuItem Header="{Binding Path=UserName}" Command="{Binding Path=ShowCommand}" CommandParameter="{Binding Path=UserAge}"/>
</HierarchicalDataTemplate>
</Window.Resources>
<Window.DataContext>
<local:MainViewModel></local:MainViewModel>
</Window.DataContext>
<StackPanel>
<Menu ItemsSource="{Binding LtUser}"></Menu>
</StackPanel>
The C# code is:
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Input;
namespace CommandParameterMVVM
{
public class MainViewModel:ViewModelBase
{
private ObservableCollection<UserModel> _LtUser;
public ObservableCollection<UserModel> LtUser
{
get { return _LtUser; }
set
{
if (_LtUser != value)
{
_LtUser = value;
RaisePropertyChanged("LtUser");
}
}
}
public MainViewModel()
{
LtUser = new ObservableCollection<UserModel>()
{
new UserModel(){UserName="Name1",UserAge="11"},
new UserModel(){UserName="Name2",UserAge="12"},
new UserModel(){UserName="Name3",UserAge="13"},
new UserModel(){UserName="Name4",UserAge="14"}
};
}
}
public class UserModel : ViewModelBase
{
private string _UserName;
public string UserName
{
get { return _UserName; }
set
{
if (_UserName != value)
{
_UserName = value;
RaisePropertyChanged("UserName");
}
}
}
private string _UserAge;
public string UserAge
{
get { return _UserAge; }
set
{
if (_UserAge != value)
{
_UserAge = value;
RaisePropertyChanged("UserAge");
}
}
}
public ICommand ShowCommand { get { return new RelayCommand<string>(OnShow); } }
private void OnShow(string obj)
{
MessageBox.Show("Age is:"+obj.ToString());
}
}
}
The result is:
Did it give you some help? If it does not, please give me more description to analyze.
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.