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 に答える