所以在我正在做的这个特定的MVVM实现中,我需要几个命令.我真的厌倦了逐个实现ICommand类,所以我提出了一个解决方案,但我不知道它有多好,所以任何WPF专家的输入都将非常感激.如果你能提供更好的解决方案,那就更好了.
我所做的是一个ICommand类和两个代理,它们将一个对象作为参数,一个委托是void(对于OnExecute),另一个是bool(对于OnCanExecute).因此,在我的ICommand的构造函数(由ViewModel类调用)中,我发送了两个方法,并在每个ICommand方法上调用委托的方法.
它的效果非常好,但我不确定这是不是一个糟糕的方法,或者是否有更好的方法.下面是完整的代码,任何输入都会非常感激,甚至是负面的,但请建设性的.
视图模型:
public class TestViewModel : DependencyObject
{
public ICommand Command1 { get; set; }
public ICommand Command2 { get; set; }
public ICommand Command3 { get; set; }
public TestViewModel()
{
this.Command1 = new TestCommand(ExecuteCommand1, CanExecuteCommand1);
this.Command2 = new TestCommand(ExecuteCommand2, CanExecuteCommand2);
this.Command3 = new TestCommand(ExecuteCommand3, CanExecuteCommand3);
}
public bool CanExecuteCommand1(object parameter)
{
return true;
}
public void ExecuteCommand1(object parameter)
{
MessageBox.Show("Executing command 1");
}
public bool CanExecuteCommand2(object parameter)
{
return true;
}
public void ExecuteCommand2(object parameter)
{ …Run Code Online (Sandbox Code Playgroud) 是否可以通过WPF中的事件调用命令?
我有一个保存按钮,按下时调用一个命令,当你完成一个文本框的编辑后,它会被按下,它也会传递一个对象作为一个命令参数
<Button Content="Save" Command="{Binding DataContext.SaveQueueTimeCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}}" CommandParameter="{Binding}" />
Run Code Online (Sandbox Code Playgroud)
我理想的做法是调用此命令并在文本框失去焦点时将对象作为参数传递,而不是必须按下按钮,例如:
<Button LostFocus="{Binding SaveQueueTimeCommand}" />
Run Code Online (Sandbox Code Playgroud)
并且仍以某种方式将对象作为参数传递.有没有办法在不使用代码的情况下实现这一点,因为我正在使用MVVM模式
谢谢你的时间