Click here to Skip to main content
15,886,110 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Dear all,

In my project I have ResourceDictionary in which I defined ControlTemplate to customize ListBoxItem. That customized ListBox is part of UserControl defined in its own separate file. When user clicks some ListBoxItem's Button a method of the same ListBoxItem shoud be called.

Does anyone know how can I accomplish this? I know how to attach method defined in code behind ResourceDictionary which ControlTemplate is defined in to Button's Click event. But I don't want to do that. I want all my UserControl's logic to be defined in one place. Any help is appreciated.

Thanks in advance.
Posted

1 solution

Provide a Name for the Button in the ControlTemplate. You can get the Button using the following statement in the CS file.
C#
Button button = GetTemplateChild(YOUR_BUTTON_NAME_IN_THE_CONTROLTEMPLATE) as Button
button.Click += OnButtonClick;


Note: This would work fine if you derive the ListBoxItem and use the above code inside the derived class.

Update :
Deleted by mistake. I don't know how to undo the delete action. :(


Mark it as answer if it is helpful
 
Share this answer
 
Comments
dsnlkc 23-Mar-11 9:16am    
@Update: Never mind. I'll write it again.

Great answer. I was completely unaware of the existence of GetTemplateChild method, probably because it's protected and thus not shown by intelisense in VS.

I have just two remarks (it may be of some help to future readers). Maybe my question wasn't clear enough, but the Button is defined in ListBoxItem's template, NOT in ListBox's one, so one should create, for example, MyListBoxItem class which should inherit from ListBoxItem class, as the note above suggests.
Also, GetTemplateChild will return button object only if the particular MyListboxItem object has Template applied to it, which is (to the best of my knowledge, but I might be wrong) done by WPF internally "when it's needed". So one could be unable to get some object defined by template in constructor of MyListBoxItem, for example. The solution for that is to explicitly apply particular template to instance of MyListBoxItem before getting its "template children" with the code above.

Thanks again for the answer. Happy codding.
Venkatesh Mookkan 23-Mar-11 12:34pm    
Thank you. Mark it as answer in that case :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900