gpt4 book ai didi

c# - 将 Command CanExecute 和 Executed 处理程序置于主窗口类之外的问题

转载 作者:行者123 更新时间:2023-11-30 21:11:15 25 4
gpt4 key购买 nike

基本上,我已经为分配给 Window.CommandBindings 的命令本身获得了一个命令绑定(bind):

<CommandBinding Command="local:TimerViewModel.AddTimer" 
CanExecute="local:TimerViewModel.AddTimer_CanExecute"
Executed="local:TimerViewModel.AddTimer_Executed" />

local是默认生成的命名空间,指向应用的命名空间。我在这里想要实现的是在 TimerViewModel 中处理命令,但我不断收到以下错误:

CanExecute="local:TimerViewModel.AddTimer_CanExecute" is not valid. 'local:TimerViewModel.AddTimer_CanExecute' is not a valid event handler method name. Only instance methods on the generated or code-behind class are valid.

虽然 TimerViewModel 非常简单,但我相信我遗漏了一些东西:

public class TimerViewModel : ViewModelBase
{
public TimerViewModel()
{
_timers = new ObservableCollection<TimerModel>();
_addTimer = new RoutedUICommand("Add Timer", "AddTimer", GetType());
}

private ObservableCollection<TimerModel> _timers;

public ObservableCollection<TimerModel> Timers
{
get { return _timers; }
}

private static RoutedUICommand _addTimer;

public static RoutedUICommand AddTimer
{
get { return _addTimer; }
}

public void AddTimer_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}

public void AddTimer_Executed(object sender, ExecutedRoutedEventArgs e)
{
_timers.Add(new TimerModel(TimeSpan.FromSeconds((new Random()).Next())));
}
}

谁能指出我犯的错误?

最佳答案

另请查看 Josh Smith 的 RelayCommand .使用它可以让你像这样写上面的内容:

public class TimerViewModel : ViewModelBase {
public TimerViewModel() {
Timers = new ObservableCollection<TimerModel>();
AddTimerCommand = new RelayCommand(() => AddTimer());
}

public ObservableCollection<TimerModel> Timers {
get;
private set;
}

public ICommand AddTimerCommand {
get;
private set;
}

private void AddTimer() {
Timers.Add(new TimerModel(TimeSpan.FromSeconds((new Random()).Next())));
}
}

关于c# - 将 Command CanExecute 和 Executed 处理程序置于主窗口类之外的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8112921/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com