How to pass a parameter in a button and get value in the code behind to redirect to another page based on the value of parameter in windows phone 7?

13,176

Solution 1

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()));
}

Solution 2

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).

Share:
13,176
Xiao Han
Author by

Xiao Han

Updated on June 04, 2022

Comments

  • Xiao Han
    Xiao Han about 2 years

    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.

  • Xiao Han
    Xiao Han over 12 years
    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
    Xiao Han over 12 years
    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
  • Teemu Tapanila
    Teemu Tapanila over 12 years
    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.