繁体   English   中英

在Windows Phone上使用MVVM进行ListBox页面导航的正确方法

[英]Correct approach to make a ListBox Page Navigation using MVVM on Windows Phone

我正在为Windows Phone构建一个应用程序,在此应用程序中,我具有带有标题,情节和图片的电影列表。 我将此列表绑定到具有自定义DataTemplate的ListBox,用于显示数据的项目。 我还创建了第二页来显示每部电影的详细信息。 我现在的问题是这些页面之间的导航。 我正在使用MVVM来构建应用程序,而我发现在Internet上搜索的大多数方法是在后面的代码中使用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在列表框上进行可视反馈。

为什么在针对MVVM的代码中处理Event? 处理事件交互是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;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM