WPF CommandParameter绑定和canExecute

Ale*_*oks 6 c# wpf delegatecommand

我有一个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>
Run Code Online (Sandbox Code Playgroud)

作为DataContext,我有一个ID为非空字段的linq实体.

问题是:如果我使用CanExecutedMethod的DelegateCommand'Add':

AddRate = new DelegateCommand<int?>(AddExecute,AddCanExecute);
Run Code Online (Sandbox Code Playgroud)

它只调用一次,参数为null(而textBlock显示正确的ID值).在调用ID属性之前调用CanExecute(使用调试器检查).似乎在绑定到实际参数之前,wpf正在调用canExecute并忘记它.绑定完成并加载正确的值后,它不会再次调用CanExecute.

作为一种解决方法,我可以使用只有执行委托的命令:

Add = new DelegateCommand<int?>(AddExecute);
Run Code Online (Sandbox Code Playgroud)

使用正确的ID值调用AddExecute并且工作正常.但我仍然想使用CanExecute功能.有任何想法吗?

alm*_*ulo 4

在这种情况下,最好对用作命令参数的属性调用 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

效果将与您的解决方案相同,但它使命令逻辑远离代码隐藏。