2011-04-12 36 views
2

我已經爲它創建了資源字典和代碼文件。 在XAML我已經定義命令綁定,並添加已執行處理程序:執行命令不在後面的資源字典代碼中觸發

<Button Grid.Row="2" Width="100" > 
    <CommandBinding Command="Search" Executed="CommandBinding_Executed" /> 
</Button> 

這裏是後面的代碼:

partial class StyleResources : ResourceDictionary { 

     public StyleResources() { 
      InitializeComponent(); 
     } 
     private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e) { 
      //this is never executed 
     } 
    } 

我不知道爲什麼不執行命令按鈕被點擊的時候,而且,爲什麼當我沒有將CanExecute設置爲true時啓用按鈕。我也嘗試將其設置爲true,但CanExecute事件並沒有觸發。 這裏是我如何使用資源字典:

public partial class MyWindow : Window { 
     public MyWindow() { 
      InitializeComponent(); 
      Uri uri = new Uri("/WPFLibs;component/Resources/StyleResources.xaml", UriKind.Relative); 
      ResourceDictionary Dict = Application.LoadComponent(uri) as ResourceDictionary; 
      this.Style = Dict["WindowTemplate"] as Style; 
     } 
    } 

回答

2

這不是你如何綁定命令按鈕。它應該是這個樣子:

<Grid> 
    <Grid.CommandBindings> 
    <CommandBinding Command="Search" 
        Executed="Search_Executed" 
        CanExecute="Search_CanExecute" /> 
    </Grid.CommandBindings> 
    ... 
    <Button Grid.Row="2" Width="100" Command="Search" /> 
    ... 
</Grid> 

而在代碼隱藏:

private void Search_Executed(object sender, ExecutedRoutedEventArgs e) { 
    // do something 
} 

private void Search_CanExecute(object sender, CanExecuteRoutedEventArgs e) { 
    e.CanExecute = ...; // set to true or false 
} 
+0

謝謝的作品! – Vale 2011-04-12 09:35:23