且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何为项目控件内的项目添加单击事件

更新时间:2023-12-06 11:03:04

This is one of the basics of UI programming even developer should know. The most primitive approach is shown here:
https://msdn.microsoft.com/en-us/library/ms743596%28v=vs.110%29.aspx[^].

However, rarely do it this way, only in cases where I want to share the same event handler in different controls. More often, I use anonymous handlers. For example,
ItemControl myParentControl = //...
UIElement item = //...
// insert/add it:
myParentControl.AddChild(item);
item.MouseDown += (sender, eventArgs) => {
   UIElement uiElement = (UIElement)sender; // or you can cast to your
                                            // more derived class
   HandleTheEventSomehow(uiElement);
   // or
   HandleTheEventInSomeOtherWay(uiElement, eventArgs.Timestamp);
}


As UIElement does not have Click event, I used MouseDown example. But you can use more derived class with Click (you just did not specify what it is), such as Button and handle this event in the same way; if you need, you can case sender to this UI element type.

See also:
https://msdn.microsoft.com/en-us/library/system.windows.uielement%28v=vs.110%29.aspx[^],
https://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol%28v=vs.110%29.aspx[^].

—SA