badmaash
badmaash

Reputation: 4845

Writing a common event bearing same functionality for two identical controls with different names

Suppose i have a XAML code that has two dialog boxes with textblocks. I have an event that's associated with the textblock on one of the dialog boxes. Can i re-use the same event in such a way for the other textblock on the other dialog box such that it handles both the elements? I dont want to create another event, copy-paste the code from the existing event and just rename the controls there or factor the common functionality into a function that accepts a textblock object. This is how i dream of laying it out:

EDIT: included additional textblocks and added to the event comments

<XamDialogWindow> 
 <TextBlock Name="ctrl1" KeyUp="keyUp_event" />
 <TextBlock Name="ctrl2" />
 ...
</XamDialogWindow>

<XamDialogWindow> 
 <TextBlock Name="ctrl3" KeyUp="keyUp_event" />
 <TextBlock Name="ctrl4" />
 ...
</XamDialogWindow>

private void keyUp_event(object o, KeyEventArgs a){ //Just one event
  //copy from one control to the other
  //For eg, if event raised from ctrl1 then copy from ctrl1 to ctrl2
}

Is this possible?

Upvotes: 0

Views: 115

Answers (2)

aditya
aditya

Reputation: 595

yeah you can directly call up the same event handler for two controls. No need of giving names to the controls also.

In the code behind if you need which control has fired the event you can do this like

String name=((TextBlock)sender).name;
if(name=="ctrl1")
    {// do something here}
else
    {//do some other here}

Upvotes: 0

MikeT
MikeT

Reputation: 5500

In XAML you don't need to name the controls at all.

so both controls will happily fire off the same handler

however you may find that having the event on the XamDialogWindow instead of the text box simplifies the matter for you as then you can check the event trail to find the source of the event and then refer to the XamDialogWindow's children to locate the other control

see OriginalSource in http://msdn.microsoft.com/en-us/library/system.windows.input.keyeventargs.aspx

Upvotes: 1

Related Questions