如果您创建一个新的 Windows Phone 项目并使用 Windows Phone 数据绑定模板,您将完成大部分工作。
您要做的是设置 ViewModel 以包含您应用的所有数据。您可以使用 IsolatedStorage 对这些数据进行序列化和反序列化,以便在应用程序会话和 Tombstoning 时保存这些数据。
在模板中,您会注意到 MailViewModel 和 ItemViewModel。 MainViewModel 存储您的应用程序需要的所有数据,包括 ItemViewModel 的 ObservableCollection,而 ItemViewModel 代表您的应用程序的单个数据类型。
在 DetailsPage.xaml 页面上,您需要将每个文本框数据绑定到 App.MainViewModel 项。如果您希望 ViewModel 在用户操作 DetailsPage.xaml 上的数据时立即更新,请将绑定设置为 TwoWay。您可以选择将 Binding 设置为 OneWay,然后使用 OK 按钮将更改写回 ViewModel 并保存到 IsolatedStorage。
下面是 Binding 的示例:
<TextBlock x:Name="ListTitle" Text="{Binding LineOne}" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
在这种情况下,LineOne 是 ItemViewModel 中的一个属性,当用户从 MainPage.xaml 中选择一个项目时,页面会从查询字符串中获取此数据。页面的 DataContext 决定了数据绑定信息的来源。
这是 MainPage 将所选项目从 ViewModel 传递到 DetailsPage 的 sn-p。
// Handle selection changed on ListBox
private void MainListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// If selected index is -1 (no selection) do nothing
if (MainListBox.SelectedIndex == -1)
return;
// Navigate to the new page
NavigationService.Navigate(new Uri("/DetailsPage.xaml?selectedItem=" + MainListBox.SelectedIndex, UriKind.Relative));
// Reset selected index to -1 (no selection)
MainListBox.SelectedIndex = -1;
}
这是 DetailsPage 如何获取所选项目的。
protected override void OnNavigatedTo(NavigationEventArgs e)
{
string selectedIndex = "";
if (NavigationContext.QueryString.TryGetValue("selectedItem", out selectedIndex))
{
int index = int.Parse(selectedIndex);
DataContext = App.ViewModel.Items[index];
}
}
使用上面的默认模板并提出任何其他问题。
数据绑定和 ObservableCollection 的美妙之处在于,您只需更新数据,用户体验就会立即反映这些变化。这是因为对数据的任何更改都会触发一个事件:
public string LineOne
{
get
{
return _lineOne;
}
set
{
if (value != _lineOne)
{
_lineOne = value;
NotifyPropertyChanged("LineOne");
}
}
}
NotifyPropertyChanged() 将此信息广播到视图。