绑定到元素时,WPF CommandParameter为NULL

时间:2013-11-29 10:41:11

标签: wpf commandparameter

我正在尝试将文本框文本绑定到Commandparameter。但是在对CanExecute的调用中,传递的参数为null。更改文本也不会调用CanExecute。

我的用例有效吗?

查看

<Window x:Class="PlayButtonCommandParameter.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:playButtonCommandParameter="clr-namespace:PlayButtonCommandParameter"
        Title="MainWindow" Height="350" Width="525">
  <Window.Resources>
    <playButtonCommandParameter:TestViewModel x:Key="vm"/>
  </Window.Resources>
    <StackPanel DataContext="{StaticResource vm}">
      <TextBox Name="Test">Hello</TextBox>
      <Button Content="Element Name Click" 
              Command="{Binding TestCommand}" 
              CommandParameter="{Binding ElementName=Test, Path=Text}"></Button>
      <Button Content="RelativeSource Click" 
              Command="{Binding RelativeSourceCommand}" 
              CommandParameter="{Binding 
                                  RelativeSource={RelativeSource AncestorType=StackPanel}, 
                                  Path=Children[0].Text}"></Button>
    </StackPanel>
</Window>

ViewModel

public class TestViewModel : INotifyPropertyChanged
{
    private readonly ICommand testCommand = new TestCommand();

    public ICommand TestCommand
    {
        get { return testCommand; }
    }

    private readonly ICommand relativeSourceCommand = new TestCommand();

    public ICommand RelativeSourceCommand
    {
        get { return relativeSourceCommand; }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

命令

public class TestCommand : ICommand
{
    public void Execute(object parameter)
    {
        Clipboard.SetData(DataFormats.Text, parameter);
    }

    public bool CanExecute(object parameter)
    {
        var text = parameter as string;

        return !string.IsNullOrEmpty(text);
    }

    public event EventHandler CanExecuteChanged;
}

1 个答案:

答案 0 :(得分:2)

没有您的期望无效。第一:

  

更改文本也不会调用CanExecute

除非您在ICommand中触发CanExecute事件,否则没有人会打电话给您CanExecuteChanged处理程序。在您的情况下,您必须自己处理TextBox TextChanged事件并从CanExecuteChanged实施中提升ICommand

对于这个简单的情况,我建议您使用RoutedCommand的实例。有一个CommandManager可以监听UI中的更改并为您举起CanExecuteChanged事件。

只需遵循以下简单步骤How to: Create a RoutedCommand

即可