【发布时间】:2014-08-17 22:47:27
【问题描述】:
在我的代码中,我有 3 个按钮。他们每个人都执行不同的事情。我让它们使用相同的命令执行,但我给了它们不同的 CommandParameter 来指定差异。
这是我所说的一个例子
XAML:
<Button Command="{Binding UpdateCommand}" CommandParameter="Add">Add Client</Button>
<Button Command="{Binding UpdateCommand}" CommandParameter="Change">Change Client</Button>
<Button Command="{Binding UpdateCommand}" CommandParameter="Remove">Remove Client</Button>
视图模型:
public MainWindowViewModel()
{
clients.Add(new Client() { Name = "Client 1" });
clients.Add(new Client() { Name = "Client 2" });
//UpdateCommand = new ClientUpdateCommand(this);
UpdateCommand = new DelegateCommand(param => ClientExecuteCommand((string)param), param => ClientCanExecuteCommand((string)param));
}
public void ClientExecuteCommand(string param)
{
ClientDialog cd;
switch(param)
{
case "Add":
cd = new ClientDialog("Add Client", "Add Client", "Random User");
cd.ShowDialog();
clients.Add(new Client() { Name = cd.nameTxtBox.Text });
break;
case "Change":
cd = new ClientDialog("Change Client", "Change Client", SelectedClient.Name);
cd.ShowDialog();
SelectedClient.Name = cd.nameTxtBox.Text;
break;
case "Remove":
clients.Remove(SelectedClient);
break;
}
}
public bool ClientCanExecuteCommand(string param)
{
if (param == "Add")
return true;
else
return !(SelectedClient == null);
}
我只是想知道这是否是不好的编程习惯,或者我是否应该为每个按钮创建不同的命令?如果这没问题;我什么时候应该不创建 CommandParameter?
提前感谢您的回答:)
【问题讨论】:
-
真的,您应该考虑围绕它的意义来设计您的命令,而不是根据需要它。在这种情况下,您有一个 Add、Change 和 Remove 标记,它们都会影响 SelectedClient。由于您以不同的方式影响相同的上下文,我会说这是完全可以接受的。
-
@Xcalibur37 这就是我的想法。感谢您的反馈:)
标签: c# wpf mvvm parameters command