开发者

Execute command does not fire in resource dictionary code behind

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 : ResourceDictio开发者_如何学运维nary {

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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜