ラッパー コマンド クラスを作成しようとしています。こんな感じで使いたい
<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 エラーは発生しませんが、Openfile
Property は呼び出されません。
編集: 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!")); }
}
}