WPF 命令参数绑定未更新 [英] WPF CommandParameter binding not updating

查看:18
本文介绍了WPF 命令参数绑定未更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 WPF 应用程序中将命令和命令参数绑定与按钮结合使用.我有这个完全相同的代码在 Silverlight 中工作得很好,所以我想知道我做错了什么!

I am trying to use Command and CommandParameter binding with Buttons in a WPF application. I have this exact same code working just fine in Silverlight so I am wondering what I have done wrong!

我有一个组合框和一个按钮,其中命令参数绑定到组合框SelectedItem:

I have a combo box and a button, where the command parameter is bound to the 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;

}

对于我的 Silverlight 应用程序,当组合框的 SelectedItem 发生变化时,CommandParameter 绑定会导致我的命令的 CanExecute 方法使用当前选定的项目重新计算,并相应地更新按钮启用状态.

With my Silverlight application, as the SelectedItem of the combobox changes, the CommandParameter binding causes the CanExecute method for my command to be re-evaluated with the currently selected item and the button enabled state is updated accordingly.

对于 WPF,出于某种原因,只有在解析 XAML 时创建绑定时才会调用 CanExecute 方法.

With WPF, for some reason, the CanExecute method is only invoked when the binding is created when the XAML is parsed.

有什么想法吗?

推荐答案

您需要告诉 WPF CanExecute 可以更改 - 您可以在 TestCommand 类中自动执行此操作,如下所示:

You need to tell WPF that CanExecute can change - you can do this automatically in your TestCommand class like this:

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

然后,每次视图中的属性更改时,WPF 都会询问 CanExecute.

WPF will then ask CanExecute everytime a property changes in the view.

这篇关于WPF 命令参数绑定未更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆