【问题标题】:Button in ListBox sending parameters from JSONListBox 中的按钮从 JSON 发送参数
【发布时间】:2013-02-27 08:27:49
【问题描述】:

在我正在创建的 Windows Phone 7.5 应用程序中,我遇到了将导航服务绑定到按钮的问题。该按钮位于 XAML 中的 ListBox 数据模板中,该模板是从 JSON 反序列化器的代码隐藏中填充的:

    void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
        if (e.Error != null)
        {
            return;
        }
        List<JSON> newslistJson = JsonConvert.DeserializeObject<List<JSON>>(e.Result);

        this.NewsList.ItemsSource = newslistJson;
    }

这里的 NewsList 列表框是通过上面的代码和一个包含“getters”和“setters”的类文件来填充的。但是,在 ListBox 和它的 DataTemplate 中,如前所述,有一个按钮:

    <Button x:Name="toNewsSite" Grid.Row="1" Content="Read More»" Height="auto" Width="auto" FontSize="19" Foreground="#FFFFFF"/>  

这个按钮应该通过第一个代码 sn-p 导航到每个项目的 news_id,这是处理公共 getter 和 setter 的类文件中的一个字符串。

所以我的梦想场景是,在代码隐藏中,webClient_DownloadString...() 中的内容如下:

toNewsSite.NavigateService = ("TheNewPage.xaml/news?id={0}", JSON.news_id);  

从那里,列表框中的每个新闻项都将有一个单独的按钮,该按钮带有一个参数,说明它具有哪个 news_id,这将在“TheNewPage”页面上获取。

这真的有用吗?

【问题讨论】:

    标签: json silverlight windows-phone-7 xaml webclient


    【解决方案1】:

    首先,Button控件没有任何NavigationService。为了导航到新页面,您需要调用 NavigationService.Navigate() 方法

    所以,我要做的就是将 id 绑定到按钮的标签

    <Button x:Name="toNewsSite" Grid.Row="1" Click="OnButtonClick" Tag="{Binding news_id}" Content="Read More»" Height="auto" Width="auto" FontSize="19" Foreground="#FFFFFF"/> 
    
    
    
    private void OnButtonClick(object sender, RoutedEventArgs e)
            {
               Button bt = (Button)sender;
               NavigationService.Navigate(new Uri("TheNewPage.xaml/news?id=" + bt.Tag.ToString(), UriKind.Relative));
            }
    

    【讨论】:

    • 我输入了相同的答案,正如你已经发布的那样......我刚刚编辑了你的答案:)
    • 嗯,谢谢!但是,当我尝试使用它时,应用程序崩溃(指向 System.Diagnostics.Debugger.Break();).. 我尝试删除参数等,但它仍然没有工作。我调试了一些断点,这里有一张图片来解释:img.ctrlv.in/512dddc369388.PNG
    • 乍一看您的 Uri 不正确,在我看来您缺少“/”,例如 Uri("/MainPage.xaml", UriKind.Relative)
    • 正常工作!非常感谢。
    • 这是一个非常笼统的问题,例如您可以根据自己的特定需求创建一个公共课程
    【解决方案2】:

    在按钮的单击处理程序中,获取按钮的 DataContext,您将能够访问

    private void OnButtonClick(object sender, RoutedEventArgs e)
    {
       JSON item = (sender as FrameworkElement).DataContext;
       NavigationService.Navigate(new Uri("TheNewPage.xaml/news?id=" + item.news_id, UriKind.Relative));
    }
    

    作为进一步的改进,我不会在 ItemTemplate 中添加按钮,而是处理您放在 DataTemplate 根目录中的任何内容的点击事件(我猜是 Grid 或 StackPanel)。

    【讨论】:

      猜你喜欢
      • 2015-03-04
      • 2020-04-09
      • 2014-01-08
      • 1970-01-01
      • 2016-10-20
      • 2012-02-14
      • 2014-03-01
      • 1970-01-01
      相关资源
      最近更新 更多