2

I have created resource dictionary and code behind file for it. In XAML I have defined command binding and added Executed handler:

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

Here is code behind:

partial class StyleResources : ResourceDictionary {

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

I don't know why is command not executing when button is clicked, and also, why is button enabled when I didn't set CanExecute to true. I have also tried to set it to true, but CanExecute event didn't fire as well. Here is how I am using the resource dictionary:

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

1 Answer 1

2

This is not how you bind commands to buttons. It should look something like this:

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

And in codebehind:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.