WPFアプリケーションでボタンを使用してCommandおよびCommandParameterバインディングを使用しようとしています。これとまったく同じコードがSilverlightで正常に機能しているので、何が間違っているのか疑問に思っています。
コンボボックスとボタンがあり、コマンドパラメーターはコンボボックスSelectedItemにバインドされています。
<Window x:Class="WPFCommandBindingProblem.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<StackPanel Orientation="Horizontal">
<ComboBox x:Name="combo" VerticalAlignment="Top" />
<Button Content="Do Something" Command="{Binding Path=TestCommand}"
CommandParameter="{Binding Path=SelectedItem, ElementName=combo}"
VerticalAlignment="Top"/>
</StackPanel>
</Window>
背後にあるコードは次のとおりです。
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
combo.ItemsSource = new List<string>(){
"One", "Two", "Three", "Four", "Five"
};
this.DataContext = this;
}
public TestCommand TestCommand
{
get
{
return new TestCommand();
}
}
}
public class TestCommand : ICommand
{
public bool CanExecute(object parameter)
{
return parameter is string && (string)parameter != "Two";
}
public void Execute(object parameter)
{
MessageBox.Show(parameter as string);
}
public event EventHandler CanExecuteChanged;
}
私のSilverlightアプリケーションでは、コンボボックスのSelectedItemが変更されると、CommandParameterバインディングにより、コマンドのCanExecuteメソッドが現在選択されている項目で再評価され、それに応じてボタンの有効状態が更新されます。
WPFでは、何らかの理由で、CanExecuteメソッドは、XAMLの解析時にバインディングが作成されたときにのみ呼び出されます。
何か案は?