<StackPanel Orientation="Horizontal" Margin="10 10 0 0" Name="deluxestack">
<Button Background="LightGreen" Command="{Binding Status}" CommandParameter="{Binding RelativeSource={RelativeSource Self}, Path=Content}" Width="30" Height="30" Content="1"/>
<Button Background="LightGreen" Command="{Binding Status}" CommandParameter="{Binding RelativeSource={RelativeSource Self}, Path=Content}" Width="30" Height="30" Content="2" Margin="10 0 0 0"/>
<Button Background="LightGreen" Command="{Binding Status}" CommandParameter="{Binding RelativeSource={RelativeSource Self}, Path=Content}" Width="30" Height="30" Content="3" Margin="10 0 0 0"/>
</StackPanel>
以上是我的代码..如何在我的viewmodel中访问这些按钮参数值(按钮的内容)?
编辑:ViewModel
public class ViewModel {
public ViewModel() {
Status = new MyCommand<int>(Receive);
}
public ICommand Status {
get; set;
}
private void Receive(int obj) {
//what should i write here??
}
}
答案 0 :(得分:0)
您可以在命令中将传递的命令参数作为对象。
在这样的视图模型中处理命令。
Status = new RelayCommand(OnbuttonClick, param => true);
现在添加处理程序如下:
private void OnbuttonClick(object obj)
{
var btnContent = obj.ToString();
}
btnContent 可能是传递的参数。
编辑: 添加了RelayCommand Class
的示例using System;
using System.Windows.Input;
namespace WpfApplication1
{
public class RelayCommand : ICommand
{
private Action<object> execute;
private Func<object, bool> canExecute;
private Action<int> receive;
private Func<object, bool> p;
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public RelayCommand(Action<object> execute, Func<object, bool> canExecute = null)
{
this.execute = execute;
this.canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
return this.canExecute == null || this.canExecute(parameter);
}
public void Execute(object parameter)
{
this.execute(parameter);
}
}
}