2009-11-17 73 views
6

我有一個TreeView項模板:WPF CommandParameter結合和canExecute

<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 NOT NULL字段LINQ實體。

的問題是:如果我使用DelegateCommand「添加」與CanExecutedMethod:

AddRate = new DelegateCommand<int?>(AddExecute,AddCanExecute); 

其稱爲只有一次,參數爲空(在文本塊顯示正確的ID值)。在調用ID屬性之前調用CanExecute(使用調試器進行檢查)。看起來像綁定到實際參數之前wpf正在調用canExecute並忘記它。一旦綁定完成並載入適當的值,它不會再次調用CanExecute。

作爲一種變通方法,我可以使用命令僅執行委託:

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

AddExecute被調用,有正確的ID值,並且可以正常使用。但我仍然想使用CanExecute功能。有任何想法嗎?

回答

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(); 
    } 
} 

效果會與您的解決方案,但它一直在指揮邏輯出的代碼隱藏。

1

我使用參數object,然後將其重新轉換回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 
    //... 
}