WPF命令参数绑定和canExecute

6

我有一个treeView项目的模板:

<HierarchicalDataTemplate x:Key="RatesTemplate">
    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding Path=ID}"/>
                        <Button CommandParameter="{Binding Path=ID}" 
                                Command="{Binding ElementName=CalcEditView, Path=DataContext.Add}">Add</Button>                            
    </StackPanel>
</HierarchicalDataTemplate>

作为一个DataContext,我有一个带有非空ID字段的linq实体。
问题是:如果我使用具有CanExecutedMethod的DelegateCommand 'Add':
AddRate = new DelegateCommand<int?>(AddExecute,AddCanExecute);

这个方法只被调用一次且参数为null(而textBlock显示正确的ID值)。在调试器中可以看到,CanExecute是在调用ID属性之前就被调用了。看起来在绑定到实际参数之前,wpf会调用CanExecute并忘记它。一旦绑定完成和正确的值被加载后,它不再调用CanExecute。

作为解决方法,我可以使用仅带有execute委托的命令:

Add = new DelegateCommand<int?>(AddExecute);

AddExecute被正确的ID值调用,并且运行得很完美。但我仍然想使用CanExecute功能。有什么建议吗?

3个回答

4
在这种情况下,最好在用作Command参数的属性上调用RaiseCanExecuteChanged()方法。在您的情况下,它将是ViewModel中的ID属性(或者您正在使用的任何DataContext)。
代码示例如下:
private int? _id;
public int? ID
{
    get { return _id; }
    set
    {
        _id = value;
        DelegateCommand<int?> command = ((SomeClass)CalcEditView.DataContext).Add;
        command.RaiseCanExecuteChanged();
    }
}

效果与您的解决方案相同,但它将命令逻辑从代码后台中分离。

2

1

我使用参数作为对象,然后将其强制转换回int

Add = new DelegateCommand<object>(add, canAdd);

在add方法中
void add(object parameter){
    int id = Convert.ToInt32(parameter);

    //or simply

    int id2 = (int)parameter;

    //...
    //  do your stuff
    //...
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接