Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling event of user control in its holding page's code behind

I am looking for a solution for following situation.

In my application i had a page say page1 and i placed a user control inside the page1. My requirement is i need to get the click event of button used in user control on page1's code behind. How i can achieve the same in windows phone / silverlight.

like image 837
StezPet Avatar asked Dec 07 '22 10:12

StezPet


2 Answers

1. The first and the right way:

(If you are aware of MVVM pattern) would be for you control, say MyControl, to expose DependencyProperty of type ICommand, named e.g. MyControlButtonClickCommand.

Xaml:

<UserControl>
    <Button Command={Binding MyControlButtonClickCommand, Source={RelativeSource Self}} />
</UserControl>  

Code-Behind:

public ICommand MyControlButtonClickCommand
{
    get { return (ICommand)GetValue(MyControlButtonClickCommandProperty); }
    set { SetValue(MyControlButtonClickCommandProperty, value); }
}

public static readonly DependencyProperty MyControlButtonClickCommandProperty =
        DependencyProperty.Register("MyControlButtonClickCommand", typeof(ICommand), typeof(MyControl), new PropertyMetadata(null));  

You'd use you UserControl as follows:

<phone:PhoneApplicationPage>

    <namespace:MyControl MyControlButtonClickCommand="{Binding ControlButtonCommand}" />

</phone:PhoneApplicationPage>

Where ControlButtonCommand is a property of a ViewModel (your custom object), living in a DataContext of your Page.

2. There is also a simpler and dirtier way which I discourage you to go:

Just like you expose MyControlButtonClickCommand dependency property and instead of exposing it, you can expose an event MyControlButtonClick and in the Page's xaml subscribe to it. Internally in your UserControl's code you should subscribe to it's button's Click event and fire its own MyControlButtonClick event.

Hope this will help you.

like image 176
Stas Shusha Avatar answered Jan 03 '23 03:01

Stas Shusha


There are two ways to do it, simplest would be double click the button on the presentation layout.

Or

in XML add onCLick= doing this would popup the menu to select new event. click on that and you event for button click should be there on the code behind.

<button name="b1" onClick="button1_Click()"/> <!--this is what ur XAML will look like -->

to handle the button click

private void button1_Click(object sender, RoutedEventArgs e)
{
    // Handle the click event here

}
like image 30
Harshit Avatar answered Jan 03 '23 04:01

Harshit