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.
(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
.
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With