我尝试编写一个包装命令类。我想这样使用它
<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!")); }
}
}