【问题标题】:WPF CommandParameter binding not updatingWPF CommandParameter 绑定未更新
【发布时间】:2011-03-06 18:15:37
【问题描述】:

我正在尝试在 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 时创建绑定时调用。

有什么想法吗?

【问题讨论】:

    标签: wpf binding command commandparameter


    【解决方案1】:

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

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

    然后,每当视图中的属性发生变化时,WPF 都会询问 CanExecute。

    【讨论】:

    • 这将重新评估 UI 上所有更改的属性的所有命令?并且没有办法将它与委托命令一起使用?有没有像 silverlight 这样更简单或 ootb 的解决方案?
    • 这只是最简单的方法——您可以控制何时调用 CanExecuteChanged 事件——在这里我只是将它设置为在框架决定它可能已更新时进行更新。
    猜你喜欢
    • 2011-08-17
    • 2010-12-17
    • 1970-01-01
    • 2011-07-19
    • 1970-01-01
    • 2015-12-27
    • 2012-05-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多