silverlight - ListBox SelectedItem 绑定(bind) : page navigation, 获取项目,在新 View 中显示其属性并重置 SelectedIndex。我能怎么做?

标签 silverlight windows-phone-7 mvvm listbox databound

我正在尝试使用 MVVM Light 在我的应用程序中应用 MVVM 模式。我有一个数据绑定(bind)列表框...

MainView.xaml [摘录]

<ListBox Name="recipesListBox" 
                             ItemsSource="{Binding RecipeList}"
                             SelectedItem="{Binding SelectedRecipe, Mode=TwoWay}"
                             HorizontalAlignment="Stretch"
                             VerticalAlignment="Stretch"
                             Grid.Row="1"
                             Margin="12,0,12,0"
                             SelectionChanged="recipesListBox_SelectionChanged" >

MainViewModel.cs [摘录]

    private Recipe selectedRecipe;

    public Recipe SelectedRecipe
    {
        get
        {
            return selectedRecipe;
        }
        set
        {
            selectedRecipe = value;
            RaisePropertyChanged("SelectedRecipe");
        }
    }

...在 SelectionChanged 上执行页面导航:

MainView.xaml.cs [摘录]

private void recipesListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string destination = "/RecipeView.xaml";
            if (recipesListBox.SelectedIndex == -1) // If selected index is -1 (no selection) do nothing
                return;
            this.NavigationService.Navigate(new Uri(destination, UriKind.Relative));
            //recipesListBox.SelectedIndex = -1; // Reset selected index to -1 (no selection)
        }

在//之后,您可以看到在页面导航后重置索引的旧代码 - 现在,使用绑定(bind)数据,显然它也将我所选择的项目设置为 null!我该如何导航到新 View ,显示所选项目的属性并在返回时重置所选索引?谢谢!

最佳答案

我的做法是这样的:

protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
{
    if (listBox.SelectedItem != null)
    {
        listBox.SelectedIndex = -1;
    }

    base.OnNavigatedFrom(e);
}

然后将以下内容添加到 SelectionChanged 事件

if(SelectedItem != null)
{
    // Do something with SelectedItem
}

关于silverlight - ListBox SelectedItem 绑定(bind) : page navigation, 获取项目,在新 View 中显示其属性并重置 SelectedIndex。我能怎么做?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11002049/

相关文章:

c# - 'await Task.Delay(5000)'之后的代码直到relaycommand执行完成才执行

c# - 在集合 MVVM 中过滤集合

xml - 通过 WCF 与 WebClient 下载图像

Silverlight与Adobe Air

windows-phone-7 - 全景页面有多少个 View 模型

windows-phone-7 - Windows Phone 7 分辨率 - 我的模拟器是在骗我吗?

c# - 提交试用版WP7应用

c# - 如何将 TreeViewItems 添加到 TreeView 控件

silverlight - 如何强制 Firefox 不缓存或重新下载 Silverlight XAP 文件?

c# - 在哪里提出 NotifyPropertyChanged?