2011-01-30 5 views
1

MVVM質問をデータバインディングMAINVIEWとItemViewモデルとセットアップMVVM - シングルページ/上の結合リストはどのようにセットアップのWindows Phoneの

あなたのビューモデルに複数のリストを持つようにしたいとしてピボット・フォームを言っていると仮定各パネルの異なるListBox。説明のために、1つのページに異なるパネル上にPeople and Placesの2つのリストボックスがあるとします。 (PeopleListとPlacesList)

どのようにViewModelsを設定しますか?各リストに1つのMainViewModelがありますか? 2つのリストを持つ1つのMainViewModel?私は、その選択に基づいて適切な詳細ページの詳細ページにナビゲートできるようにしたいと思います。

第2に、フォームが読み込まれるときに、どのようにして各リストボックスを別のビューモデルにバインドしますか。

私の混乱は、フォームがロードされたときにコンテキストを単一の静的変数に設定し、各リストボックスの異なるソースを指定する方法がわからないことを示すようです。

以下は、サンプルのコードスニペットです。質問のいくつかに

DataContext = App.ViewModel ; 


    public class MainViewModel : INotifyPropertyChanged 
    { 
     public MainViewModel() 
     { 
      this.Items = new ObservableCollection<ItemViewModel>(); 
//?? can you have more than one of these? 
     } 

//?? should I have Public MainViewModel2() with this.Items = new OC<IVM2> 
//... 

/// Creates and adds a few ItemViewModel objects into the Items collection. 
     /// </summary> 
     public void LoadData() 
     { 
      this.Items.Add(new ItemViewModel() { VAR1 = "X", VAR2 = "Y"}) ; 

 

<Grid x:Name="LayoutRoot" Background="Transparent" > 
      <!--Pivot Control--> 
     <controls:Pivot x:Name="Pivot" Title="MyApp" DataContext="{Binding}" Loaded="Pivot_Loaded"> 
      <!--Pivot item one--> 

... 

    <!--Pivot item two--> 
      <controls:PivotItem Header="people"> 

       <Grid> 
        <ListBox x:Name="PeopleList" Height="442" HorizontalAlignment="Left" Margin="46,68,0,0" VerticalAlignment="Top" Width="346" ItemsSource="{Binding ItemsA}" SelectionChanged="ListBox1_SelectionChanged" /> 
       </Grid> 

<!--Pivot item three--> 
      <controls:PivotItem Header="places"> 

       <Grid> 
        <ListBox x:Name="PlacesList" Height="442" HorizontalAlignment="Left" Margin="46,68,0,0" VerticalAlignment="Top" Width="346" ItemsSource="{Binding ItemsB}" SelectionChanged="ListBox2_SelectionChanged" /> 
      </Grid> 

答えて

2

回答:

どのように多くの/のviewmodels?

必ずここにMainViewModelがあるはずです。そしてMainViewModelは種類PeopleListViewModelPlacesListViewModel、または

  • 2つのリスト・プロパティObservableCollection<PersonViewModel>ObservableCollection<PlaceViewModel>

    • 2つのプロパティを持っていること。はい、あなたが好きなだけ多くを持つことができますが、ItemsAとItemsBを呼び出すのが最良の選択ではありません。

    最初のオプションでは、リストを保持する2つのビュー(UserControls)を作成します。

    2番目のオプションでは、ItemsControlとDataTemplateを使用してリストを表示できます。

    一般に、MVVMでは、SelectedItemChangedやその他のイベントを回避しようとします。 SelectedItemプロパティにデータバインド(ビューのセクション)することができます。

  • +0

    これは非常に役に立ちました。 –