【问题标题】:how to binding ICommand from MainWindow Class in WPF?如何从 WPF 中的 MainWindow 类绑定 ICommand?
【发布时间】: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


    【解决方案1】:

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

    buttonStrat.DataContext = this;
    

    在 xaml 中使用这个:

    Command="{Binding StartButtonCommand}"
    

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

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

    【讨论】:

      猜你喜欢
      • 2015-04-02
      • 2018-09-05
      • 1970-01-01
      • 2015-11-13
      • 1970-01-01
      • 2013-08-05
      • 2012-06-11
      • 1970-01-01
      • 2013-01-06
      相关资源
      最近更新 更多