4

I am thinking if the windows phone 7 button event is similar to ASP.NET development with C#, something like in the button, I set value to commandparameter in the XAML, and in the code behind, I get the commandparameter and redirect the page.

I haven't found any good examples for button event handling, any suggestions?

Thank you.

Dima Pasko
  • 1,170
  • 12
  • 20
Xiao Han
  • 1,004
  • 7
  • 16
  • 33
  • I am trying to do something like and I want to get the Title from the Button_Click event handler at code behind. – Xiao Han Jan 17 '12 at 01:17

2 Answers2

12

For the xaml:

<Button Tag="pageAddress" Click="Button_Click" />

And then on the code-behind:

private void Button_Click(object sender, RoutedEventArgs e)
{
     Button _button = (Button)sender;
     NavigationService.Navigate(new System.Uri(_button.Tag.ToString()));
}
robsiemb
  • 6,157
  • 7
  • 32
  • 46
Teemu Tapanila
  • 1,275
  • 8
  • 20
  • 2
    Thank you for your reply. What difference between using Tag property and CommandParameter property? I guess I can do Tag="{Binding Title}" same as CommandParameter="{Binding Title}" ? – Xiao Han Jan 17 '12 at 01:19
  • Hi Teemu, would you be able to give me a short example how can I pass Item object which has Icon, LineOne, LineTwo and LineThree properties to another page using Tag within Button control, please? I found the Tag property in Button control is really useful when passing an object. Thank you very much – Xiao Han Jan 17 '12 at 10:00
  • 1
    I normally use MVVM and with that the Tag property is perfect for referring items. I can't really fit the whole Tag example into this comment. – Teemu Tapanila Jan 19 '12 at 18:55
9

I would recommend you use a command parameter as you mentioned. So in your xaml do something like this:

<Button x:name="myButton" CommandParameter="{Binding Title}" Click="myButton_Click"/>

And in your C# code something like this:

private void myButton_Click(object sender, RoutedEventArgs e)
{
    Button _myButton = (Button)sender;
    string value = _myButton.CommandParameter.ToString();
}

Really it's pretty similar to Teemu's answer although I must admit I haven't used the Tag element before. According to the documentation on MSDN, the Tag element should work pretty nicely as it can store custom information that you can access in your code behind (or viewmodel).

amaitland
  • 4,073
  • 3
  • 25
  • 63
Edward
  • 7,346
  • 8
  • 62
  • 123