質問

WPFアプリケーションでボタンを使用したコマンドおよびコマンドパラミー計のバインディングを使用しようとしています。私はこのまったく同じコードがシルバーライトでうまく機能しているので、私は何が間違っているのか疑問に思っています!

コンボボックスとボタンがあり、コマンドパラメーターがCombobox 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;

}

Comboboxの選択項目が変更されると、Silverlightアプリケーションを使用すると、CommandParameter Bindingは、現在選択されているアイテムでコマンドのCanexecuteメソッドを再評価し、それに応じてボタン有効な状態が更新されます。

WPFでは、何らかの理由で、Canexecuteメソッドは、XAMLが解析されたときにバインディングが作成されたときにのみ呼び出されます。

何か案は?

役に立ちましたか?

解決

Canexecuteが変更できることをWPFに伝える必要があります - このようなTestCommandクラスでこれを自動的に実行できます。

public event EventHandler CanExecuteChanged
{
    add{CommandManager.RequerySuggested += value;}
    remove{CommandManager.RequerySuggested -= value;}
}

その後、WPFは、プロパティがビューに変更されるたびにCanexecuteを要求します。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top