极品分享

C#触发按钮的事件

 1、

 

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

        private void button2_Click(object sender, EventArgs e)
        {
            button1_Click(null,null);
        }

 

2、 

以编程的方式调用Button的点击事件

在Winform中,可以使用MyBtn.PerformClick()调用MyBtn的Click事件。

在wpf中呢?可以这样做:

using System.Windows.Automation.Peers;

using System.Windows.Automation.Provider;
 
  private void DoButtonClick()
 {
             ButtonAutomationPeer bam = new ButtonAutomationPeer(MyBtn);
             IInvokeProvider iip = bam.GetPattern(PatternInterface.Invoke) as IInvokeProvider;
             iip.Invoke();
 }

 

 

调用Window的Close方法,通过这个方法去触发Closing事件,比如:

Xaml

<Window x:Class="WindowClosingEvent.MainWindow"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        AllowsTransparency="false" WindowStyle="None"

        Foreground="{x:Null}" Background="#FF626060"

        Title="MainWindow" Width="400" Height="613" AllowDrop="True" Closing="Window_Closing" BorderThickness="2"WindowState="Normal">

    <Grid>

        <Button Click="Button_Click"/>

    </Grid>

</Window>

 

Code-Behind

 

namespace WindowClosingEvent

{

    public partial class MainWindow : Window

    {

        public MainWindow()

        {

            InitializeComponent();

        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)

        {

            MessageBoxResult message =MessageBox.Show("Do you want to close""System Message",MessageBoxButton.YesNo,MessageBoxImage.Warning);

 

            if (message ==MessageBoxResult.No)

            {

                e.Cancel =true;

            }

        }

 

        private void Button_Click(object sender, RoutedEventArgs e)

        {

            this.Close();

            //Application.Current.Shutdown();

        }

    }

}

 

上面的例子,我通过this.Close()方法成功的触发了Closing事件。

2013-04-24 0 /
NET学习
/
标签: 

评论回复

回到顶部