I have a ListBox that has a style defined for ListBoxItems. Inside this style, I have some labels and a button. One that button, I want to define a click event that can be handled on my page (or any page that uses that style). How do I create an event handler on my WPF page to handle the event from my ListBoxItems style?
Here is my style (affected code only):
<Style x:Key='UsersTimeOffList' TargetType='{x:Type ListBoxItem}'> ... <Grid> <Button x:Name='btnRemove' Content='Remove' Margin='0,10,40,0' Click='btnRemove_Click' /> </Grid> </Style>
Thanks!
Take a look at RoutedCommands.
Define your command in myclass somewhere as follows:
Now define your button with this command:
You can use CommandParameter for extra information..
Now last but not least, start listening to your command:
In the constructor of the class you wish to do some nice stuff, you place:
or in XAML:
And you implement the delegate the CommandBinding needs:
You can start listening to this command everywhere in your visual tree!
Hope this helps
PS You can also define the CommandBinding with a CanExecute delegate which will even disable your command if the CanExecute says so 🙂
PPS Here is another example: RoutedCommands in WPF