代码之家  ›  专栏  ›  技术社区  ›  Jonas Follesø

第一次调用CanExecute时,WPF CommandParameter为NULL

  •  75
  • Jonas Follesø  · 技术社区  · 17 年前

    <ItemsControl 
        x:Name="commentsList"
        ItemsSource="{Binding Path=SharedDataItemPM.Comments}"
        Width="Auto" Height="Auto">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <Button                             
                        Content="Delete"
                        FontSize="10"
                        Command="{Binding Path=DataContext.DeleteCommentCommand, ElementName=commentsList}" 
                        CommandParameter="{Binding}" />
                </StackPanel>                       
             </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
    

    更新:

    更新2:

    我已将该漏洞的复制品上载到我的SkyDrive: http://cid-1a08c11c407c0d8e.skydrive.live.com/self.aspx/Code%20samples/CommandParameterBinding.zip

    14 回复  |  直到 17 年前
        1
  •  58
  •   Travis Weber    16 年前

    我在试图绑定视图模型上的命令时遇到了同样的问题。

    旧代码:

    Command="{Binding DataContext.MyCommand, ElementName=myWindow}"
    

    新代码:

    Command="{Binding DataContext.MyCommand, RelativeSource={RelativeSource AncestorType=Views:MyView}}"
    

    :我只是在没有使用ElementName的情况下遇到了这个问题,我正在绑定到视图模型上的一个命令,并且按钮的数据上下文是我的视图模型。在本例中,我只需在按钮声明(在XAML中)中将CommandParameter属性移到Command属性之前。

    CommandParameter="{Binding Groups}"
    Command="{Binding StartCommand}"
    
        2
  •  32
  •   Ed Ball    17 年前

    我发现设置Command和CommandParameter的顺序会产生不同。设置Command属性会导致立即调用CanExecute,因此您希望CommandParameter已在该点设置。

    您似乎暗示按钮永远不会启用,这是令人惊讶的,因为在您的示例中,我希望CommandParameter在Command属性之后不久设置。调用CommandManager.InvalidateRequestSuggested()是否会导致按钮变为启用状态?

        3
  •  17
  •   David Liersch    17 年前

    public class TriggerConverter : IMultiValueConverter
    {
        #region IMultiValueConverter Members
    
        public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            // First value is target value.
            // All others are update triggers only.
            if (values.Length < 1) return Binding.DoNothing;
            return values[0];
        }
    
        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    
        #endregion
    }
    

    此值转换器接受任意数量的参数,并将第一个参数作为转换后的值传回。在您的案例中,在多重绑定中使用时,它如下所示。

    <ItemsControl 
        x:Name="commentsList"
        ItemsSource="{Binding Path=SharedDataItemPM.Comments}"
        Width="Auto" Height="Auto">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <Button                             
                        Content="Delete"
                        FontSize="10"
                        CommandParameter="{Binding}">
                        <Button.Command>
                            <MultiBinding Converter="{StaticResource TriggerConverter}">
                                <Binding Path="DataContext.DeleteCommentCommand"
                                         ElementName="commentsList" />
                                <Binding />
                            </MultiBinding> 
                        </Button.Command>
                    </Button>
                </StackPanel>                                       
             </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
    

    您必须将TriggerConverter作为资源添加到某个地方才能使其工作。现在,在CommandParameter的值变为可用之前,不会设置Command属性。您甚至可以绑定到RelativeSource.Self和CommandParameter而不是。达到同样的效果。

        4
  •  14
  •   StayOnTarget Charlie Flowers    6 年前

    我想出了另一个解决这个问题的办法,我想和大家分享一下。因为命令的CanExecute方法是在设置CommandParameter属性之前执行的,所以我创建了一个带有附加属性的帮助器类,该属性在绑定更改时强制再次调用CanExecute方法。

    public static class ButtonHelper
    {
        public static DependencyProperty CommandParameterProperty = DependencyProperty.RegisterAttached(
            "CommandParameter",
            typeof(object),
            typeof(ButtonHelper),
            new PropertyMetadata(CommandParameter_Changed));
    
        private static void CommandParameter_Changed(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var target = d as ButtonBase;
            if (target == null)
                return;
    
            target.CommandParameter = e.NewValue;
            var temp = target.Command;
            // Have to set it to null first or CanExecute won't be called.
            target.Command = null;
            target.Command = temp;
        }
    
        public static object GetCommandParameter(ButtonBase target)
        {
            return target.GetValue(CommandParameterProperty);
        }
    
        public static void SetCommandParameter(ButtonBase target, object value)
        {
            target.SetValue(CommandParameterProperty, value);
        }
    }
    

    <Button 
        Content="Press Me"
        Command="{Binding}" 
        helpers:ButtonHelper.CommandParameter="{Binding MyParameter}" />
    

    我希望这也许能帮助其他人解决这个问题。

        5
  •  10
  •   Simon Smith    10 年前

    CommandParameter="{Binding .}"
    

    到

    CommandParameter="{Binding DataContext, RelativeSource={RelativeSource Self}}"
    

        6
  •  7
  •   Ralf Stauder    7 年前

    <MenuItem Header="Open file" Command="{Binding Tag.CommandOpenFile, IsAsync=True, RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}" CommandParameter="{Binding Name}" />
    

    Tag CommandParameter Command IsAsync=True CanExecute 调用)一位,因此该参数已可用。不过,这意味着,在很短的一段时间内,启用状态可能是错误的,但对我来说,这是完全可以接受的。

        7
  •  5
  •   Swythan    17 年前

    CommandParameterBehavior 我把它贴到了 Prism forums 昨天它添加了缺少的行为,其中 CommandParameter Command

    这里有一些复杂的原因,因为我试图避免在调用时导致的内存泄漏 PropertyDescriptor.AddValueChanged PropertyDescriptor.RemoveValueChanged

    您可能需要删除 IDelegateCommand 除非您使用的是Prism(并且希望对Prism库进行与我相同的更改),否则请填充。还请注意,我们通常不使用 RoutedCommand 在这里(我们使用棱镜的 DelegateCommand<T> CommandManager.InvalidateRequerySuggested

    using System;
    using System.ComponentModel;
    using System.Windows;
    using System.Windows.Input;
    
    namespace Microsoft.Practices.Composite.Wpf.Commands
    {
        /// <summary>
        /// This class provides an attached property that, when set to true, will cause changes to the element's CommandParameter to 
        /// trigger the CanExecute handler to be called on the Command.
        /// </summary>
        public static class CommandParameterBehavior
        {
            /// <summary>
            /// Identifies the IsCommandRequeriedOnChange attached property
            /// </summary>
            /// <remarks>
            /// When a control has the <see cref="IsCommandRequeriedOnChangeProperty" />
            /// attached property set to true, then any change to it's 
            /// <see cref="System.Windows.Controls.Primitives.ButtonBase.CommandParameter" /> property will cause the state of
            /// the command attached to it's <see cref="System.Windows.Controls.Primitives.ButtonBase.Command" /> property to 
            /// be reevaluated.
            /// </remarks>
            public static readonly DependencyProperty IsCommandRequeriedOnChangeProperty =
                DependencyProperty.RegisterAttached("IsCommandRequeriedOnChange",
                                                    typeof(bool),
                                                    typeof(CommandParameterBehavior),
                                                    new UIPropertyMetadata(false, new PropertyChangedCallback(OnIsCommandRequeriedOnChangeChanged)));
    
            /// <summary>
            /// Gets the value for the <see cref="IsCommandRequeriedOnChangeProperty"/> attached property.
            /// </summary>
            /// <param name="target">The object to adapt.</param>
            /// <returns>Whether the update on change behavior is enabled.</returns>
            public static bool GetIsCommandRequeriedOnChange(DependencyObject target)
            {
                return (bool)target.GetValue(IsCommandRequeriedOnChangeProperty);
            }
    
            /// <summary>
            /// Sets the <see cref="IsCommandRequeriedOnChangeProperty"/> attached property.
            /// </summary>
            /// <param name="target">The object to adapt. This is typically a <see cref="System.Windows.Controls.Primitives.ButtonBase" />, 
            /// <see cref="System.Windows.Controls.MenuItem" /> or <see cref="System.Windows.Documents.Hyperlink" /></param>
            /// <param name="value">Whether the update behaviour should be enabled.</param>
            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;
                }
    
                var fce = source as FrameworkContentElement;
                if (fce != null)
                {
                    fce.Unloaded += OnUnloaded;
                }
            }
    
            private static void UnhookUnloaded(object source)
            {
                var fe = source as FrameworkElement;
                if (fe != null)
                {
                    fe.Unloaded -= OnUnloaded;
                }
    
                var fce = source as FrameworkContentElement;
                if (fce != null)
                {
                    fce.Unloaded -= OnUnloaded;
                }
            }
    
            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();
                }
    
            }
        }
    }
    
        8
  •  1
  •   Joe Bako    16 年前

    有一种相对简单的方法可以通过DelegateCommand“修复”此问题,尽管它需要更新DelegateCommand源代码并重新编译Microsoft.Practices.Composite.Presentation.dll。

    1) 下载Prism 1.2源代码并打开CompositeApplicationLibrary_Desktop.sln。这里是一个Composite.Presentation.Desktop项目,其中包含DelegateCommand源。

    public event EventHandler CanExecuteChanged
    {
         add
         {
              WeakEventHandlerManager.AddWeakReferenceHandler( ref _canExecuteChangedHandlers, value, 2 );
              // add this line
              CommandManager.RequerySuggested += value;
         }
         remove
         {
              WeakEventHandlerManager.RemoveWeakReferenceHandler( _canExecuteChangedHandlers, value );
              // add this line
              CommandManager.RequerySuggested -= value;
         }
    }
    

    protected virtual void OnCanExecuteChanged()
    {
         // add this line
         CommandManager.InvalidateRequerySuggested();
         WeakEventHandlerManager.CallWeakReferenceHandlers( this, _canExecuteChangedHandlers );
    }
    

    4) 重新编译解决方案,然后导航到已编译DLL所在的调试或发布文件夹。将Microsoft.Practices.Composite.Presentation.dll和.pdb(如果愿意)复制到引用外部程序集的位置,然后重新编译应用程序以获取新版本。

    乔

        9
  •  1
  •   kkCosmo    10 年前

    public event EventHandler CanExecuteChanged;
    

    我把它改成:

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

    我删除了以下两种方法,因为我太懒了,无法修复它们

    public void RaiseCanExecuteChanged()
    

    和

    protected virtual void OnCanExecuteChanged()
    

    Application.Current?.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)CommandManager.InvalidateRequerySuggested);
    
        10
  •  0
  •       17 年前

    嘿,Jonas,我不确定这在数据模板中是否有效,但下面是我在ListView上下文菜单中使用的绑定语法,用于获取当前项作为命令参数:

        12
  •  0
  •   TravisWhidden    10 年前

    其中一些答案是关于绑定到DataContext以获取命令本身,但问题是CommandParameter在不应该为空时为空。我们也经历过这种情况。凭直觉,我们找到了一种在ViewModel中实现这一点的简单方法。这是专门针对客户报告的CommandParameter null问题的,只有一行代码。请注意Dispatcher.BeginInvoke()。

    public DelegateCommand<objectToBePassed> CommandShowReport
        {
            get
            {
                // create the command, or pass what is already created.
                var command = _commandShowReport ?? (_commandShowReport = new DelegateCommand<object>(OnCommandShowReport, OnCanCommandShowReport));
    
                // For the item template, the OnCanCommand will first pass in null. This will tell the command to re-pass the command param to validate if it can execute.
                Dispatcher.BeginInvoke((Action) delegate { command.RaiseCanExecuteChanged(); }, DispatcherPriority.DataBind);
    
                return command;
            }
        }
    
        13
  •  -1
  •   Dennis    17 年前

    这是不可能的。要对此进行调试,您可以尝试:
    -正在检查PreviewCanExecute事件。
    -使用snoop/wpf mole窥视内部并查看commandparameter是什么。

    嗯,,

        14
  •  -1
  •       17 年前

    commandManager.invalidatereQuerySuggestized也适用于我。我相信下面的链接讨论了类似的问题,M$dev确认了当前版本中的限制,而commandManager.InvalidateRequestSuggestized就是解决方法。 http://social.expression.microsoft.com/Forums/en-US/wpf/thread/c45d2272-e8ba-4219-bb41-1e5eaed08a1f/

    调用commandManager.InvalidateRequestSuggested的时间是什么。这应该在通知相关值更改后调用。

        15
  •  -2
  •   Sebastian Negraszus    7 年前

    在旁边 Ed Ball's suggestion 关于设置 命令参数 命令 ,确保 CanExecute

    private bool OnDeleteSelectedItemsCanExecute(object SelectedItems)  
    {
        // Your goes heres
    }
    

    希望它可以防止有人花费大量的时间来找出如何接收SelectedItems作为CanExecute参数

    推荐文章