列表6:主视图页面后台关键代码
namespace WP7SterlingLearning
{
public partial class MainPage : PhoneApplicationPage
{
public MainPage()
{
InitializeComponent();
DataContext = App.ViewModel;
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
}
private void MainListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (MainListBox.SelectedIndex == -1)
return;
NavigationService.Navigate(new Uri("/ContactList.xaml?selectedGroup=" + MainListBox.SelectedIndex, UriKind.Relative));
MainListBox.SelectedIndex = -1;
}
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
if (!App.ViewModel.IsDataLoaded)
{
App.ViewModel.LoadData();
}
}
}
}
{
public partial class MainPage : PhoneApplicationPage
{
public MainPage()
{
InitializeComponent();
DataContext = App.ViewModel;
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
}
private void MainListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (MainListBox.SelectedIndex == -1)
return;
NavigationService.Navigate(new Uri("/ContactList.xaml?selectedGroup=" + MainListBox.SelectedIndex, UriKind.Relative));
MainListBox.SelectedIndex = -1;
}
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
if (!App.ViewModel.IsDataLoaded)
{
App.ViewModel.LoadData();
}
}
}
}
首先,在MainPage类的构造函数中,我们把DataContext属性绑定到App.ViewModel。这一点很重要,也展示了整个系统的用户描述层是如何实现的。
接下来,让我们来分析一下MainPage_Loaded方法-每次示例页面加载时都调用这个方法。预先检查一下是否有必要再次加载视图模型数据是一个很好的设计习惯。
最后一点值得注意的是ListBox控件的SelectionChanged事件处理程序。在这个方法中,我们首先判断用户是否点击了ListBox控件中的项目之一。如果没有选中某个项目,即可返回;否则,我们把当前用户导航到另一个网页ContactList.xaml,以显示对应于所选组对应的联系人信息。注意,在页面ContactList.xaml的OnNavigatedTo事件处理器中我们传递进参数selectedGroup。
至于页面ContactList.xaml,有点复杂,但仍然很容易理解。首先,让我们来看一下这个页面的XAML标记代码的情况。
列表7: 页面ContactList.xaml的XAML标记代码
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<ListBox x:Name="MainListBox" Margin="0,0,-12,0" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Margin="0,0,0,17" Width="432">
<TextBlock Text="{Binding GroupId}" TextWrapping="Wrap"
Style="{StaticResource PhoneTextExtraLargeStyle}"/>
<TextBlock Text="{Binding Id}" TextWrapping="Wrap" Margin="12,-6,12,0"
Style="{StaticResource PhoneTextSubtleStyle}"/>
<TextBlock Text="{Binding Name}" TextWrapping="Wrap"
Style="{StaticResource PhoneTextExtraLargeStyle}"/>
<TextBlock Text="{Binding Email}" TextWrapping="Wrap" Margin="12,-
6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
<ListBox x:Name="MainListBox" Margin="0,0,-12,0" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Margin="0,0,0,17" Width="432">
<TextBlock Text="{Binding GroupId}" TextWrapping="Wrap"
Style="{StaticResource PhoneTextExtraLargeStyle}"/>
<TextBlock Text="{Binding Id}" TextWrapping="Wrap" Margin="12,-6,12,0"
Style="{StaticResource PhoneTextSubtleStyle}"/>
<TextBlock Text="{Binding Name}" TextWrapping="Wrap"
Style="{StaticResource PhoneTextExtraLargeStyle}"/>
<TextBlock Text="{Binding Email}" TextWrapping="Wrap" Margin="12,-
6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>