自定义命令中的DependencyProperty

时间:2012-10-09 14:21:19

标签: c# wpf

我尝试编写一个包装器命令类。我希望像这样使用它

<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!")); }
    }
}

1 个答案:

答案 0 :(得分:3)

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

但要明确的是,你为什么要这样做呢?什么错了

<Button Content="Test" Command="{Binding OpenFile}">
</Button>