我正在创建一个应用程序,我从DB Via Web服务获取数据并将其显示在我的mainpage.xaml中的列表框中(有关正在举行的不同事件的数据,例如EventTitle,Date等)目前我已设置这样,当选择列表框中的项目时,应用程序将导航到“EventDetail”页面,该页面仅列出列表中的选定数据。
我需要帮助的是获取此用户选择的数据并将其带到要使用的导航页面。我正在努力以最简单的方式解决问题;如何将用户选择的列表框项目传输到已定义的页面,以更清晰的方式显示它并使用此数据。
优选地,我想在导航页面内的单独文本块中显示每个文本块/单元格(EventTitle,Date等),以便它们可以被适当地布局,但是仅具有所选字段数据的列表框将完成该工作。
以下是相关的Xaml代码:
<ListBox Height="496" HorizontalAlignment="Left" Margin="-4,155,0,0" Name="FirstListBox2" VerticalAlignment="Top" Width="460" SelectionChanged="FirstListBox2_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Height="132">
<StackPanel Width="370">
<TextBlock Text="{Binding EventID}" Foreground="#FFC8AB14" FontSize="24" />
<TextBlock Text="{Binding EventList}" TextWrapping="Wrap" FontSize="36" />
<TextBlock Text="{Binding Date}" TextWrapping="Wrap" FontSize="24" />
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
以下是相关的C#编码:
private void FirstListBox2_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
EventServiceReference1.Event myEvent = (EventServiceReference1.Event)FirstListBox2.SelectedItem;
NavigationService.Navigate(new Uri("/EventPageTemp.xaml", UriKind.Relative));
}
如果你能帮助我解决这个问题,我将非常感激。
答案 0 :(得分:1)
使用query-string参数发送所选值:
EventServiceReference1.Event myEvent = (EventServiceReference1.Event)FirstListBox2.SelectedItem;
int eventId = myEvent.EventID;
string url = string.Format("/EventPageTemp.xaml?eventId={0}", eventId);
NavigationService.Navigate(new Uri(url, UriKind.Relative));
您可以pick up the event parameter on the target page使用NavigationContext.QueryString
。然后根据需要设置目标页面的数据上下文:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
int eventId;
string eventIdStr;
if (NavigationContext.QueryString.TryGetValue("eventId", out eventIdStr) && int.TryParse(eventIdStr, out eventId))
{
// load event data, and set data context
}
}
修改强>
我想你可能想暂时保存事件数据,而不是从目标页面上的服务重新加载它。如果是这样,您可以使用独立存储来保存事件数据。因此,在导航之前,使用适当的密钥添加数据:
IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
settings["event"] = myEvent;
settings["eventId"] = eventId;
然后以同样的方式拿起它:
IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
if (settings.ContainsKey("event") && (int)settings["eventId"] == eventId)
{
var myEvent = (EventServiceReference1.Event)settings["event"];
}
编辑#2
正如AndreiC所指出的,写入隔离存储会占用设备上的空间,因此您应该删除不再需要的任何项目。
答案 1 :(得分:1)
一种简单的方法是将类型为Event的公共静态属性添加到App类(将其命名为SelectedEvent),这样当用户从ListBox中选择一个事件时,您将设置:
App.SelectedEvent = myevent;
然后在EventPageTemp.xaml.cs中,您只需将页面的DataContext设置为App.SelectedEvent:
DataContext = App.SelectedEvent;
在EventPageTemp的xaml页面中,您只需将接口绑定到Event对象的属性即可。