0

我正在为 Windows Phone 构建一个应用程序,在这个应用程序中,我有一个带有标题、情节和图片的电影列表。我将此列表绑定到具有自定义 DataTemplate 的 ListBox,用于显示数据的项目。我还创建了第二个页面来显示每部电影的详细信息。我现在的问题是这些页面之间的导航。我正在使用 MVVM 构建应用程序,我在互联网上搜索的大多数方法是在代码隐藏中使用 OnSelectionChanged 事件,但这与我想要的相反,即使用 MVVM。

我见过的其他方法,这是我正在尝试的方法,是将 SelectedItem 绑定到 ViewModel 中的属性,但我无法让它更改属性,似乎我无法在列表框中选择一个项目. 此外,当我按下列表框中的一项时,我没有视觉反馈,例如我们在手机设置菜单中的反馈。

我在列表框中使用的代码是:

<ListBox Margin="0,0,-12,0" ItemsSource="{Binding Movies}" SelectedItem="{Binding SelectedMovieItem}" SelectionMode="Single" >
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal" Margin="0,0,0,17">
                            <!--Replace rectangle with image-->
                            <Rectangle Height="50" Width="50" Fill="#FFE5001b" Margin="12,0,9,0"/>
                            <StackPanel Width="311">
                                <TextBlock Text="{Binding Name}" TextWrapping="NoWrap" Style="{StaticResource PhoneTextExtraLargeStyle}" Foreground="#000" />
                                <!--<TextBlock Text="{Binding LineTwo}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>-->
                            </StackPanel>
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>

我见过的另一种方法是使用 INavigationService 来实现这一点,我发现这篇文章: http: //windowsphonegeek.com/articles/MVVM-in-real-life-Windows-Phone-applications-Part1 我阅读了第一个部分和两个,但我无法理解这个工作。

所以,我想知道的是我使用的方法是否适合进行页面导航,或者是否有更好的方法使用 MVVM 来通过列表框上的视觉反馈来做到这一点。

4

1 回答 1

1

为什么在针对 MVVM 的代码中处理事件?处理事件交互是 UI 的一部分。当然,您不会在那里编写所有逻辑代码。但是您只是想转到下一页。我做这样的事情:

    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("/Views/detailsPage.xaml?selectedItem=" + MainListBox.SelectedIndex, UriKind.Relative));

        // Reset selected index to -1 (no selection)
        MainListBox.SelectedIndex = -1;
    }
于 2012-07-01T08:32:31.853 回答