【发布时间】:2012-03-25 18:39:46
【问题描述】:
我正在尝试在 MainWindow 的按钮命令上绑定 ICommand 属性。但它不起作用。 这是我尝试的示例代码。
C# 代码:
public partial class MainWindow : Window
{
private ICommand _StartButtonCommand;
public ICommand StartButtonCommand
{
get{ return this._StartButtonCommand;}
set
{
if (this._StartButtonCommand!=value)
{
this._StartButtonCommand = value;
}
}
}
public MainWindow()
{
InitializeComponent();
this.StartButtonCommand = new ReplayCommand(new Action<object>(startButtonCommandEx));
}
private void startButtonCommandEx(object obj)
{
MessageBox.Show("Done");
}
protected class ReplayCommand : ICommand
{
private Action<object> _action;
public ReplayCommand(Action<object> action)
{
this._action = action;
}
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
try
{
if (parameter!=null)
{
this._action(parameter);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "AutoShutdown", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
}
XAML:
<Button x:Name="buttonStrat" Content="Start" HorizontalAlignment="Left" Width="84.274" Height="39.246" Command="{Binding StartButtonCommand, ElementName=window}"/>
实际上,我想使用 ICommand 访问 UI 元素,如 DataGridView SelectedItem 属性或任何其他 UI 属性,s why i am writing ICommand in MainWindow Class.
I dont 知道这是正确的方式还是错误的方式。我只是尝试一下,我没有成功。如果是错误的方法,请告诉我什么是正确的方法以及如何做。
感谢您的建议。
【问题讨论】:
标签: c# .net wpf data-binding mvvm