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

本文关键字:参数 routedeventhandler Phone Window | 更新日期: 2023-09-27 17:58:27

我正试图将参数传递给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));
}

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

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

您可以将参数添加到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类型,因此您可以输入参数、集合、字符串等的数组。

更改您的:

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时,它被称为
它用于获取传递的值,就像查询字符串一样。

希望这对有帮助