MVVM ICommand.CanExecute参数包含以前的值

时间:2015-02-13 15:00:10

标签: c# wpf mvvm icommand delegatecommand

如果使用嵌套属性而不是普通属性,我很难理解为什么ICommand.CanExecutes总是包含先前的值而不是新值。

下面描述了这个问题,除了使用某种形式的“Facade”模式之外,我真的无法找到解决这个问题的方法,我在viewmodel中创建属性并将它们挂钩到模型中的相应属性。

或者使用该死的CommandManager.RequerySuggested事件。这不是最佳的原因是因为视图提供了超过30个命令,只计算菜单,如果每次更改时所有CanExecute更新,则所有菜单项/按钮都需要几秒钟更新。即使使用下面的示例只使用一个命令和按钮以及命令管理器,按钮也需要大约500ms来启用/禁用自身。

我能想到的唯一原因是在触发CanExecute之前没有更新CommandParameter绑定,然后我猜你无能为力。

提前致谢:!

例如

假设我们有这个基本的viewmodel

public class BasicViewModel : INotifyPropertyChanged
{
    private string name;
    public string Name
    {
        get { return name; }
        set {
            this.name = value;
            RaisePropertyChanged("Name");
            Command.RaiseCanExecuteChanged();
        }
    }

    private Project project;

    public Project Project
    {
        get { return project; }
        set {
            if (project != null) project.PropertyChanged -= ChildPropertyChanged;
            if (value != null) value.PropertyChanged += ChildPropertyChanged;

            project = value;
            RaisePropertyChanged("Project");
        }
    }

    private void ChildPropertyChanged(object sender, PropertyChangedEventArgs e) {
        Command.RaiseCanExecuteChanged();
    }

    public DelegateCommand<string> Command { get; set; }

    public BasicViewModel()
    {
        this.Project = new Example.Project();
        Command = new DelegateCommand<string>(this.Execute, this.CanExecute);
    }

    private bool CanExecute(string arg) {
        return !string.IsNullOrWhiteSpace(arg);
    }

    private void Execute(string obj) { }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void RaisePropertyChanged(string propertyName = null) {
        if (this.PropertyChanged != null)
            this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

和这个模型

public class Project : INotifyPropertyChanged
{
    private string text;

    public string Text
    {
        get { return text; }
        set
        {
            text = value;
            RaisePropertyChanged("Text");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void RaisePropertyChanged(string propertyName = null)
    {
        var handler = this.PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

现在我认为我有这个文本框和按钮。

<Button Content="Button" CommandParameter="{Binding Path=Project.Text}" Command="{Binding Path=Command}" />
<TextBox Text="{Binding Path=Project.Text, UpdateSourceTrigger=PropertyChanged}" />

它有效,每次在文本框中键入内容时,都会调用CanExecute,但参数始终设置为前一个值。假设我在文本框中写'H',将参数设置为NULL触发CanExecute。接下来我写'E',现在文本框包含“HE”,CanExecute再次触发。这次参数设置为“H”。

由于某些奇怪的原因,参数始终设置为上一个值,当我检查Project.Text时,它设置为“HE”,但参数仍设置为“H”。

如果我现在将命令参数更改为

CommandParameter="{Binding Path=Name}"

和Textbox.Text到

Text={Binding Path=Name, UpdateSourceTrigger=PropertyChanged}"

一切都很完美。 CanExecute参数始终包含最新值,而不是之前的值。

3 个答案:

答案 0 :(得分:0)

您正在谈论的外观模式标准WPF实践。您执行此操作的方式的主要问题是,当引发事件时,其订阅的事件处理程序按订阅它们的顺序执行。您拥有的代码行:

        if (value != null) value.PropertyChanged += ChildPropertyChanged;

这订阅了&#34; PropertyChanged&#34;您&#34;项目&#34;的活动类。您的UIElements也订阅了同样的&#34; PropertyChanged&#34;通过XAML中的绑定事件。简而言之,您的&#34; PropertyChanged&#34;活动现在有2个订阅者。

关于事件的事情是,它们按顺序触发,代码中发生的事情是,当事件从您的&#34; Project.Text&#34;它执行你的&#34; ChildPropertyChanged&#34;事件,解雇你的&#34; CanExecuteChanged&#34;事件,最终运行你的&#34; CanExecute&#34;功能(当你看到不正确的参数时)。 然后,在那之后,您的UIElements将由同一事件执行其EventHandler。并且他们的价值得到了更新。

导致问题的订阅顺序。试试这个并告诉我它是否解决了你的问题:

public Project Project
{
    get { return project; }
    set {
        if (project != null) project.PropertyChanged -= ChildPropertyChanged;
        project = value;
        RaisePropertyChanged("Project");
        if (project != null) project.PropertyChanged += ChildPropertyChanged;
    }
}

答案 1 :(得分:0)

我就是这样做的,它按预期工作。这里唯一的区别是我使用RelayCommand而不是DelegateCommand - 它们基本上具有相同的实现,因此它们应该是可互换的。

当用户输入文本然后单击按钮时,RelayCommand的execute方法将获得预期的文本 - 简单。

XAML:

<Grid>

    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>

    <TextBox Grid.Column="0"
             Grid.Row="0"
             Text="{Binding Path=Text, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />

    <Button Grid.Column="0"
            Grid.Row="1"
            Content="Test"
            VerticalAlignment="Bottom"
            HorizontalAlignment="Center"
            Command="{Binding Path=TextCommand, Mode=OneWay}" />

</Grid>

视图模型:

public sealed class ExampleViewModel : BaseViewModel
{
    private string _text;

    public ExampleViewModel()
    {
       TextCommand = new RelayCommand(TextExecute, CanTextExecute);
    }

    public string Text
    {
        get
        {
            return _text;
        }
        set
        {
            _text = value;
            OnPropertyChanged("Text");
        }
    }

    public ICommand TextCommand { get; private set; }

    private void TextExecute()
    {
        // Do something with _text value...
    }

    private bool CanTextExecute()
    {
        return true;
    }
}

答案 2 :(得分:0)

我在swism codeplex讨论论坛上找到了swythan的这个很棒的附加属性,它很好地完成了这个工作。当然,它没有回答为什么命令参数设置为先前的值,但它以一种很好的方式解决了问题。

代码稍微从源代码修改,通过在调用OnLoaded事件时调用HookCommandParameterChanged,可以在TabItem中的控件上使用它。

public static class CommandParameterBehavior
{
    public static readonly DependencyProperty IsCommandRequeriedOnChangeProperty =
        DependencyProperty.RegisterAttached("IsCommandRequeriedOnChange",
                                            typeof(bool),
                                            typeof(CommandParameterBehavior),
                                            new UIPropertyMetadata(false, new PropertyChangedCallback(OnIsCommandRequeriedOnChangeChanged)));

    public static bool GetIsCommandRequeriedOnChange(DependencyObject target)
    {
        return (bool)target.GetValue(IsCommandRequeriedOnChangeProperty);
    }

    public static void SetIsCommandRequeriedOnChange(DependencyObject target, bool value)
    {
        target.SetValue(IsCommandRequeriedOnChangeProperty, value);
    }

    private static void OnIsCommandRequeriedOnChangeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (!(d is ICommandSource))
            return;

        if (!(d is FrameworkElement || d is FrameworkContentElement))
            return;

        if ((bool)e.NewValue)
            HookCommandParameterChanged(d);
        else
            UnhookCommandParameterChanged(d);

        UpdateCommandState(d);
    }

    private static PropertyDescriptor GetCommandParameterPropertyDescriptor(object source)
    {
        return TypeDescriptor.GetProperties(source.GetType())["CommandParameter"];
    }

    private static void HookCommandParameterChanged(object source)
    {
        var propertyDescriptor = GetCommandParameterPropertyDescriptor(source);
        propertyDescriptor.AddValueChanged(source, OnCommandParameterChanged);

        // N.B. Using PropertyDescriptor.AddValueChanged will cause "source" to never be garbage collected,
        // so we need to hook the Unloaded event and call RemoveValueChanged there.
        HookUnloaded(source);
    }

    private static void UnhookCommandParameterChanged(object source)
    {
        var propertyDescriptor = GetCommandParameterPropertyDescriptor(source);
        propertyDescriptor.RemoveValueChanged(source, OnCommandParameterChanged);

        UnhookUnloaded(source);
    }

    private static void HookUnloaded(object source)
    {
        var fe = source as FrameworkElement;
        if (fe != null)
        {
            fe.Unloaded += OnUnloaded;
            fe.Loaded -= OnLoaded;
        }

        var fce = source as FrameworkContentElement;
        if (fce != null)
        {
            fce.Unloaded += OnUnloaded;
            fce.Loaded -= OnLoaded;
        }
    }

    private static void UnhookUnloaded(object source)
    {
        var fe = source as FrameworkElement;
        if (fe != null)
        {
            fe.Unloaded -= OnUnloaded;
            fe.Loaded += OnLoaded;
        }

        var fce = source as FrameworkContentElement;
        if (fce != null)
        {
            fce.Unloaded -= OnUnloaded;
            fce.Loaded += OnLoaded;
        }
    }

    static void OnLoaded(object sender, RoutedEventArgs e)
    {
        HookCommandParameterChanged(sender);
    }

    static void OnUnloaded(object sender, RoutedEventArgs e)
    {
        UnhookCommandParameterChanged(sender);
    }

    static void OnCommandParameterChanged(object sender, EventArgs ea)
    {
        UpdateCommandState(sender);
    }

    private static void UpdateCommandState(object target)
    {
        var commandSource = target as ICommandSource;

        if (commandSource == null)
            return;

        var rc = commandSource.Command as RoutedCommand;
        if (rc != null)
            CommandManager.InvalidateRequerySuggested();

        var dc = commandSource.Command as IDelegateCommand;
        if (dc != null)
            dc.RaiseCanExecuteChanged();
    }
}

来源:https://compositewpf.codeplex.com/discussions/47338