2010-06-22 88 views
7

我想要在WPF應用程序中使用Command和CommandParameter綁定按鈕。我有這個完全相同的代碼在Silverlight中工作得很好,所以我想知道我做錯了什麼!WPF CommandParameter綁定不更新

我有一個組合框和一個按鈕,其中命令參數綁定到ComboBox的SelectedItem:

<Window x:Class="WPFCommandBindingProblem.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="MainWindow" Height="350" Width="525"> 
    <StackPanel Orientation="Horizontal"> 
     <ComboBox x:Name="combo" VerticalAlignment="Top" /> 
     <Button Content="Do Something" Command="{Binding Path=TestCommand}" 
       CommandParameter="{Binding Path=SelectedItem, ElementName=combo}" 
       VerticalAlignment="Top"/>   
    </StackPanel> 
</Window> 

後面的代碼如下:

public partial class MainWindow : Window 
{ 
    public MainWindow() 
    { 
     InitializeComponent(); 

     combo.ItemsSource = new List<string>(){ 
      "One", "Two", "Three", "Four", "Five" 
     }; 

     this.DataContext = this; 

    } 

    public TestCommand TestCommand 
    { 
     get 
     { 
      return new TestCommand(); 
     } 
    } 

} 

public class TestCommand : ICommand 
{ 
    public bool CanExecute(object parameter) 
    { 
     return parameter is string && (string)parameter != "Two"; 
    } 

    public void Execute(object parameter) 
    { 
     MessageBox.Show(parameter as string); 
    } 

    public event EventHandler CanExecuteChanged; 

} 

隨着我的Silverlight應用程序,隨着組合框的SelectedItem更改,CommandParameter綁定將使用我的命令的CanExecute方法使用當前選定的項目重新評估,並且按鈕啓用狀態會相應更新。

對於WPF,出於某種原因,CanExecute方法僅在分析XAML時創建綁定時纔會調用。

任何想法?

回答

8

你需要告訴WPF是CanExecute可以改變 - 你可以在你TestCommand類自動執行此操作是這樣的:那麼

public event EventHandler CanExecuteChanged 
{ 
    add{CommandManager.RequerySuggested += value;} 
    remove{CommandManager.RequerySuggested -= value;} 
} 

WPF會問CanExecute每次視圖中的屬性更改。

+0

這將重新評估UI上所有屬性更改的所有命令?並沒有辦法與委託命令一起使用它? Silverlight中沒有簡單的或者不合適的解決方案嗎? – Firo 2013-01-18 15:15:56

+0

這只是最簡單的方法 - 你控制何時調用CanExecuteChanged事件 - 在這裏我只是設置它來更新,只要框架決定它可能已經更新。 – Goblin 2013-01-21 07:50:05