【问题标题】:Correct approach to make a ListBox Page Navigation using MVVM on Windows Phone在 Windows Phone 上使用 MVVM 制作列表框页面导航的正确方法
【发布时间】:2012-07-01 07:51:42
【问题描述】:

我正在为 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 通过列表框上的视觉反馈来做到这一点。

【问题讨论】:

    标签: c# mvvm windows-phone


    【解决方案1】:

    为什么要在针对 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;
        }
    

    【讨论】:

    • 我想在我的软件中打开其他页面,难道没有另一种方法,用ViewModel中的逻辑吗?
    • 我试过你说的,显示我选择的项目的MessageBox,现在还有一个问题,我点击一个项目时没有视觉反馈。
    • 那么 ViewModel 应该对视图一无所知。在这里,您只是试图从一种视图移动到另一种视图。您如何尝试显示消息框?
    • 即使有视觉反馈,我也设法让它工作,我关注了这篇文章link。现在唯一要做的就是将数据传递到另一个页面,我该怎么做?我是否必须像在网页中一样在 uri 中将其作为参数传递?
    • 哦,不好意思,没注意到你在代码里放了页面间传递数据的解决方案!完美的!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多