如何在WPF中绑定MainWindow类的ICommand?

时间:2012-03-25 18:39:46

标签: c# .net wpf data-binding mvvm

我尝试在MainWindow的Button命令上绑定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 Elements Like DataGridView SelectedItem属性或任何其他UI属性,s why i am writing ICommand in MainWindow Class. I don知道这是正确的方法。我只是尝试一下,但我没有成功。如果是错误的方式,请告诉我什么是正确的方法以及如何做到这一点。

感谢s的建议。

1 个答案:

答案 0 :(得分:1)

首先,您没有在按钮上设置DataContext

buttonStrat.DataContext = this;

在xaml中使用它:

Command="{Binding StartButtonCommand}"

另外,为了缩短您的代码,您可以将您的属性更改为:

public ICommand StartButtonCommand
{
    get { return new ReplayCommand(new Action<object>(startButtonCommandEx)); }
}