2

我已经为它创建了资源字典和代码隐藏文件。在 XAML 中,我定义了命令绑定并添加了 Executed 处理程序:

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

1 回答 1

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
}
于 2011-04-12T09:13:01.833 回答