Window Phone 7 C#在routedeventhandler中传递参数

时间:2011-06-06 21:56:53

标签: c# windows-phone-7

我正在尝试将参数传递给RoutedEventHandler

中使用的函数
Button start = new Button();
start.Click += new RoutedEventHandler(playSelectedAlarm_Click);

private void playSelectedAlarm_Click(object sender, EventArgs e)
{
    NavigationService.Navigate(new Uri("/AlarmPicker.xaml", UriKind.Relative));
}

我该怎么做?或者有更好的方法吗?

2 个答案:

答案 0 :(得分:2)

您可以将参数添加到Button的Tag属性中。然后,在事件处理程序中提取它们:

Button start = new Button();
start.Tag = new string[] { "param1", "param2" };
start.Click += new RoutedEventHandler(playSelectedAlarm_Click);

private void playSelectedAlarm_Click(object sender, EventArgs e)
{        
    //extract the parameters and cast to a `string[]`
    var myParameters = (string[])((Button)sender).Tag;
    string p1 = myParameters[0]; //value is "param1"
    string p2 = myParameters[1]; //value is "param2"


    NavigationService.Navigate(new Uri("/AlarmPicker.xaml", UriKind.Relative));
}

Tag属性需要object类型,因此您可以输入参数,集合,字符串等数组。

答案 1 :(得分:0)

改变你的:

NavigationService.Navigate(new Uri("/AlarmPicker.xaml", UriKind.Relative));

var uri = "/AlarmPicker.xaml?idx=" + url + "&title=" + title);
NavigationService.Navigate(new Uri(uri, UriKind.Relative));

之后,在AlarmPicker.xaml.cs添加此内容:

out string m_Link = string.empty;
out string m_Title = string.empty;
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
    base.OnNavigatedTo(e);

    NavigationContext.QueryString.TryGetValue("idx", out m_Link);
    NavigationContext.QueryString.TryGetValue("title", out m_Title);

    Console.Writeline("IDX: " + m_link);
    Console.Writeline("TITLE: " + m_Title);
}

加载AlarmPicker.xaml 时称为
它用于获取传递的值,如查询字符串。

希望这会有所帮助