0
votes

In the Windows Phone 7.5 application I'm creating, I've got a problem with binding a navigationservice to a button. The button is inside a ListBox datatemplate in XAML, which is populated from codebehind from a JSON deserializer:

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

The NewsList listbox is here populated via the code above, and a class file containing and the "getters" and "setters". However, inside the ListBox and it's DataTemplate, as stated earlier, there's a button:

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

This button should, via the first code snippet, navigate to each of the items' news_id, which is a string in the class file handling the public getters and setters.

So my dream scenario here would be, in codebehind, something like this inside the webClient_DownloadString...():

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

Aaand from there each of the news items in the listbox will have an individual button with a parameter stating which news_id it has, which will be fetched on the "TheNewPage" page.

Would this actually work?

2

2 Answers

3
votes

First of all, Button control do not have any NavigationService. Inorder to navigate to navigate to a new page, you need to call NavigationService.Navigate() method

So, What i would do is to bind the id to the Tag of the Button

<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));
        }
1
votes

In the click handler for the button grab the DataContext of the button and you'll be able to access the

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

As a further improvement, rather than adding a button to the ItemTemplate, I'd handle the tap event of whatever you put at the root of the DataTemplate (I'd guess a Grid or StackPanel).