#502 – Sender 和RoutedEventArgs.Source的区别(Sender vs. RoutedEventArgs.Source)

本文详细解释了WPF中RoutedEvent的处理机制,特别是如何使用RoutedEventArgs.Source和sender参数来确定事件的触发源和事件处理函数的所有者。通过一个具体的按钮点击事件示例展示了这两者的区别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

但你处理RoutedEvent 或者其子类的的时候,你可以通过RoutedEventArgs.Source 属性来获得事件的来源,同时事件处理函数同样也有一个sender 参数来指出事件的来源。

在路由事件中,RoutedEventArgs.Source 是引发事件的控件的引用,而sender 是事件处理程序拥有者的引用。

在下面的例子中,RoutedEventArgs.SourceButton 类型的引用。而sender 则是StackPanel 类型的引用,因为它拥有Click 事件处理函数。

<StackPanel ButtonBase.Click="Button_Click">
    <Button Content="Keaton" />
    <Button Content="Chaplin" />
    <Button Content="Arbuckle" />
</StackPanel>
private void Button_Click(object sender, RoutedEventArgs e)
{
    Button b = e.Source as Button;
    MessageBox.Show(string.Format("You clicked on {0} button, sender is of type {1}",
        b.Content, sender.GetType().ToString()));
}

原文地址:https://wpf.2000things.com/2012/02/27/502-sender-vs-routedeventargs-source/


Unhandled exception. System.InvalidCastException: Unable to cast object of type &#39;WpfApp1.Models.ProductType&#39; to type &#39;System.Windows.Controls.ComboBoxItem&#39;. at WpfApp1.Views.Window5.btnReader_Click(Object sender, RoutedEventArgs e) in E:\c#\WpfApp1\WpfApp1\Views\Window5.xaml.cs:line 37 at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised) at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args) at System.Windows.Controls.Primitives.ButtonBase.OnClick() at System.Windows.Controls.Button.OnClick() at System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e) at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target) at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised) at System.Windows.UIElement.ReRaiseEventAs(DependencyObject sender, RoutedEventArgs args, RoutedEvent newEvent) at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target) at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised) at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args) at System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args) at System.Windows.Input.InputManager.ProcessStagingArea() at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport) at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel) at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean& handled) at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, In
03-19
using FT2_SoildState.DataAccess; using FT2_SoildState.Model; using FT2_SoildState.View; using FT2_SoildState.ViewModel; using System; using System.Collections.Generic; using System.Data; using System.Diagnostics; using System.IO; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace FT2_SoildState { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { private bool IsInvaildClosedWindow = false; public MainWindow() { InitializeComponent(); this.DataContext = Model.UpdateViewDisplay.mainWindowViewModel; UpdateViewDisplay.UpdateHandlerConnectStateDisplay(false); } private void Grid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { DragMove(); } private void Btn_SystemSetting(object sender, RoutedEventArgs e) { View.SystemSettingView setter = new(); setter.ShowDialog(); UpdateViewDisplay.UpdateTestModeDisplay(); UpdateViewDisplay.UpdateChipTypeDisplay(); UpdateViewDisplay.UpdateTargetTemperatureDisplay(); } private void Btn_ZoomWindow(object sender, RoutedEventArgs e) { if (this.WindowState == WindowState.Maximized) this.WindowState = WindowState.Normal; else this.WindowState = WindowState.Maximized; } private void Btn_CloseWindow(object sender, RoutedEventArgs e) { if (IsInvaildClosedWindow || (MessageBox.Show("是否确认关闭应用", "警告", MessageBoxButton.YesNo) == MessageBoxResult.Yes)) { Close(); } } private void Btn_CBInfo(object sender, RoutedEventArgs e) { View.CBInfo info = new(); info.ShowDialog(); } private void Btn_ConfigIP(object sender, RoutedEventArgs e) { View.ConfigCBIP cbip = new(); cbip.ShowDialog(); } private void Btn_ModifyPassword(object sender, RoutedEventArgs e) { View.ModifyPassword modifyPassword = new(); modifyPassword.ShowDialog(); } private void Btn_UpdateSCMFireware(object sender, RoutedEventArgs e) { View.UpdateSCMFireware update = new(); update.ShowDialog(); } private void Btn_ShowAbout(object sender, RoutedEventArgs e) { View.About about = new(); about.ShowDialog(); } private void Btn_OpenSimu(object sender, RoutedEventArgs e) { if (File.Exists(@".\SimuHandler\SimuHandler.exe")) Process.Start(@".\SimuHandler\SimuHandler.exe"); else MessageBox.Show(System.Environment.CurrentDirectory + ".\\SimuHandler\\SimuHandler.exe 文件不存在。", "Error"); } private void SwitchLoginRoleIcon() { var image = Btn_SwitchUser.Content as Image; switch (Model.Global.LoginRole) { case Model.Global.E_ROLE.ADMIN: if (image != null) { image.Source = new BitmapImage( new Uri("pack://application:,,,/FT2_Soildstate;component/Images/Administrator.png") ); } break; case Model.Global.E_ROLE.OPERATOR: if (image != null) { image.Source = new BitmapImage( new Uri("pack://application:,,,/FT2_Soildstate;component/Images/Operator.png") ); } break; case Global.E_ROLE.RD: if (image != null) { image.Source = new BitmapImage( new Uri("pack://application:,,,/FT2_Soildstate;component/Images/RD.png") ); } break; } } private void Window_Loaded(object sender, RoutedEventArgs e) { //1. rd debug flag if (Model.Whitelist.ThisComputerInWhitelist()) Model.Global.IsBackdoor = true; DataAccess.INI.ReadShrdSpecified(); if (!Model.Global.IsBackdoor) { //if (Model.BUPR.IsRegisterApplication() == false) //{//判断是否有注册; // View.AppRegisterView regView = new() { // Topmost = true // }; // regView.ShowDialog(); // if (Model.BUPR.IsRegisterApplication() == false) // { // IsInvaildClosedWindow = true; // this.Close(); // return; // } //} //2.启动登入界面 View.LoginView loginView = new(); loginView.Topmost = true; if (loginView.ShowDialog() == false) { IsInvaildClosedWindow = true; this.Close(); return; } switch (Model.Global.LoginRole) { case Global.E_ROLE.RD: break; case Global.E_ROLE.ADMIN: this.WindowStyle = WindowStyle.None; this.WindowState = WindowState.Maximized; break; case Global.E_ROLE.OPERATOR: this.WindowStyle = WindowStyle.None; this.WindowState = WindowState.Maximized; this.Menu_Download.Visibility = Visibility.Collapsed; break; } } // SwitchLoginRoleIcon(); DispFrame.Navigate(new FramePage.Page_BoardNumber44()); //switch (Model.Global.CH_NUM) //{ // case 44: // DispFrame.Navigate(new FramePage.Page_BoardNumber44()); // break; // case 120: // DispFrame.Navigate(new FramePage.Page_BoardNumber120()); // break; // case 60: // DispFrame.Navigate(new FramePage.Page_BoardNumber60()); // break; // default: // break; //} UpdateViewDisplay.UpdateLoginRoleStateDisplay(Model.Global.LoginRole); UpdateViewDisplay.UpdateTestModeDisplay(); UpdateViewDisplay.UpdateChipTypeDisplay(); UpdateViewDisplay.UpdateTargetTemperatureDisplay(); //启动线程 Thread thread1 = new Thread(Model.BUPR.ThreadFunc_MQProcess) { IsBackground = true }; thread1.Start(); Thread thread2 = new Thread(Model.BUPR.ThreadFunc_CheckIsConnectToHandler) { IsBackground = true }; thread2.Start(); //启动定时器 Model.BUPR.InitMyTimer(); Global.IsStartupApp = true; } private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) { DataAccess.Log.SaveToLogBuf("", true); //写入log buf Thread.Sleep(1000); } private void DispFrame_Navigated(object sender, NavigationEventArgs e) { } private void Btn_SwitchUser_Click(object sender, RoutedEventArgs e) { View.LoginView loginView = new(); loginView.ShowDialog(); LoginName = newUserName; switch (Model.Global.LoginRole) { case Global.E_ROLE.ADMIN: this.Menu_Download.Visibility = Visibility.Visible; break; case Global.E_ROLE.OPERATOR: this.Menu_Download.Visibility = Visibility.Collapsed; break; } SwitchLoginRoleIcon(); } } } 帮我看看是少了什么
最新发布
08-16
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值