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

これにより、コマンドからの MessageBox が常に表示されますDefaultValue。へのバインディングはOpenFile機能しません。BindingExpression エラーは発生しませんが、OpenfileProperty は呼び出されません。

編集: 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または設定してみてくださいSourceRelativeSourceツリーをトラバースすることを忘れないでください。どちらも機能しません。追加PresentationTraceSources.TraveLevel=Highして、実際の問題を自分で確認します。

しかし、明確にするために、なぜとにかくこれを試しているのですか?どうしたの

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