button1.PerformClick() in wpf

后端 未结 7 1596
难免孤独
难免孤独 2020-12-15 21:07

Why this code in WPF does not work ?

private void button1_Click(object sender, EventArgs e)
    {
        MessageBox.Show(\"yes\");
    }
    pr         


        
7条回答
  •  感情败类
    2020-12-15 22:07

    Good practice in WPF is using commands. It improves testability and separates UI and business logic.

    First you may try RoutedUICommand.

    
    
        
    
    
        

    In code behind file we have to define RoutedClickCommand and Execute|CanExecute handlers:

        public static ICommand RoutedClickCommand = new RoutedUICommand("ClickCommand", "ClickCommand", typeof(MainWindow));
    
        private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;
        }
    
        private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            MessageBox.Show("ololo");
        }
    

    So, when you need button logic ("button1.PerformClick();" in your sample), just put next line:

    MainWindow.RoutedClickCommand.Execute(null);
    

    As for me, I preffer another way which supposes carry command into presentation model. Composite Application Library (Prism) helps me with its DelegateCommand class. Then command definition in presentation model looks like:

        private DelegateCommand _clickCommand;
    
        public ICommand ClickCommand
        {
            get
            {
                if (this._clickCommand == null)
                {
                    this._clickCommand = new DelegateCommand(p =>
                        {
                            //command logic
                        },
                        p =>
                        { 
                            // can execute command logic
                        });
                }
                return this._clickCommand;
            }
        }
    
    
    

    And view XAML and code behind:

    
    
        

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.Model = new SampleModel();
        }
    
        protected SampleModel Model
        {
            get
            {
                if (this.Model.ClickCommand.CanExecute())
                {
                    this.Model.ClickCommand.Execute();
                }
                return (SampleModel)this.DataContext;   
            }
            set 
            {
                this.DataContext = value;
            }
        }
    }
    

    Next code calls command in view bypassing clicking on button:

    if (this.Model.ClickCommand.CanExecute())
    {
     this.Model.ClickCommand.Execute();
    }
    

    提交回复
    热议问题