1

我尝试编写一个包装命令类。我想这样使用它

<Button Content="Test">
  <Button.Command>
    <local:FileOpenCommand Command="{Binding OpenFile}"/>
  </Button.Command>
</Button>

到目前为止我尝试了什么:

public class FileOpenCommand : FrameworkElement, ICommand
{
    public static readonly DependencyProperty CommandProperty =
      DependencyProperty.RegisterAttached("Command",
        typeof(ICommand),
        typeof(FileOpenCommand),
        new FrameworkPropertyMetadata(CommandChanged)
        {
            DefaultValue = new RelayCommand(
               (ob) => MessageBox.Show(ob.ToString()))
        });

    public ICommand Command
    {
        get { return (ICommand)this.GetValue(CommandProperty); }
        set { this.SetValue(CommandProperty, value); }
    }

    public static void CommandChanged(
         DependencyObject d, DependencyPropertyChangedEventArgs e) { /* ... */ }

    public bool CanExecute(object parameter) { /*...*/ }

    public event System.EventHandler CanExecuteChanged;

    public void Execute(object parameter)
    {
        var dlg = new OpenFileDialog();
        if (dlg.ShowDialog())
        {
            Command.Execute(dlg.FileName);
        }
    }
}

这始终显示DefaultValue命令中的 MessageBox。绑定OpenFile不起作用。我没有收到 BindingExpression 错误,但Openfile从未调用过该属性。

编辑:MainWindow 代码

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;
    }

    public ICommand OpenFile
    {
        get { return new RelayCommand(
                 (obj) => MessageBox.Show("I want to see this!")); }
    }
}
4

1 回答 1

3

FileOpenCommand不是视觉或逻辑树的一部分,因此你没有继承DataContext,因此你Binding不能工作。尝试使用ElementName或设置明确的Source. 记住RelativeSource遍历树也不会工作。添加PresentationTraceSources.TraveLevel=High以自己检查实际问题。

但要清楚,你为什么要尝试这个呢?有什么问题

<Button Content="Test" Command="{Binding OpenFile}">
</Button>
于 2012-10-09T15:20:47.703 回答