【发布时间】:2015-04-13 06:49:32
【问题描述】:
我正在尝试实施here 中描述的错误验证解决方案,但我想不出办法。在顶部响应中,方法
private void CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = IsValid(sender as DependencyObject);
}
正在从视图接收发送者和 CanExecuteRoutedEventArgs。这意味着该方法必须在视图中实现。这是怎么回事? CanExecute 是 Command 类的属性,只能在 viewmodel 类中使用。由于从 ICommand 接口派生只允许以下实现:
public bool CanExecute(object parameter)
{
throw new NotImplementedException();
}
我应该如何在视图模型中接收有关对象的信息并将它们传递给命令的 CanExecute 方法?
这是我当前的实现,我已经尝试过解决这个问题,但如果不将方法传递给委托,它是无用的。
查看:
<Button Command="{Binding Path=GenerateBinaryFileCommand}">
<Button.CommandBindings>
<CommandBinding CanExecute="CanExecute"/>
</Button.CommandBindings>
</Button>
View.cs:
private void CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
ViewModel vm = (ViewModel )DataContext;
e.CanExecute = vm.IsValid(sender as DependencyObject);
}
ViewModel.cs:
private DelegateCommand generateBinaryCommand;
public bool IsValid(DependencyObject obj)
{
// The dependency object is valid if it has no errors and all
// of its children (that are dependency objects) are error-free.
return !Validation.GetHasError(obj) &&
LogicalTreeHelper.GetChildren(obj)
.OfType<DependencyObject>()
.All(IsValid);
}
public ICommand GenerateBinaryFileCommand
{
get
{
if (generateBinaryCommand == null)
{
// here is where I need to pass the CanExecute method
generateBinaryCommand = new DelegateCommand(generateBinary);
}
return generateBinaryCommand;
}
}
【问题讨论】:
-
看看这个链接是否对你有帮助。 stackoverflow.com/questions/28393307/…
标签: c# wpf validation mvvm sender