2

MVVMLightを使用してアプリケーションにMVVMパターンを適用しようとしています。私はデータバインドされたリストボックスを持っています...

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)
        }

//後、ページナビゲーション後にインデックスをリセットする古いコードを見ることができます-バインドされたデータを使用すると、明らかに、選択したアイテムもnullに設定されます!新しいビューに移動し、選択したアイテムのプロパティを表示し、戻ったときに選択したインデックスをリセットするにはどうすればよいですか?ありがとうございました!

4

2 に答える 2

1

最良の方法は、コレクションをどこにでもアクセスできる場所に保存し(Windows Phoneデータバインドアプリケーションプロジェクトなど)、選択したアイテムのインデックスをナビゲーションuriに渡すことです。

int index = recipesListBox.SelectedIndex;
this.NavigationService.Navigate(new Uri(destination +"?index="+index , UriKind.Relative));

次に、新しいページのOnNavigatedToメソッドで、クエリからインデックスを取得し、アイテムを取得します

override OnNavigatedTo(
{
    string index;
    if(NavigationContext.QueryString.TryGetValue("index", index))
    {
        // get the item from your collection based on this index
    }

}
于 2012-06-12T17:57:42.637 に答える
1

私がそれをした方法はこれでした:

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
}
于 2012-06-13T21:32:28.407 に答える