3

こんにちは、MVVMとWin8アプリの開発について学び、XAMLを介してObservableCollection(NoteViewModel.csにあります)をMainPageリストボックス(またはリストビュー)にバインドするのに問題があります。

public ObservableCollection<Note> NotesList;

モデルは単純なNote.csクラスであり、NoteText、Priority、およびRemindDateを保持します。

私が今していることは、MainPage.xaml.csの分離コードファイルのDataContextをObservableCollectionに設定することです。

public MainPage()
{
    this.InitializeComponent();
    NoteViewModel nvm = new NoteViewModel();
    noteListView.DataContext = nvm.NotesList;
}

そして、NoteViewModelコンストラクターで、2つの新しいNotesを作成し、それをコレクションに追加します。

私がやりたいのは、XAMLのDataContextをNoteViewModelに設定し、ItemsSourceをNotesListに設定することです。後で単一のノートにDetailsViewを実装したいと思います。

コレクションをリストボックスにバインドするチュートリアルはたくさんありますが、MVVMを正しく実行する方法を示すチュートリアルは見つかりませんでした。

何か助けはありますか?

4

3 に答える 3

3

リストのDataContextをコレクションに設定するのではなく、ビュー(MainPage)をViewModelにバインドする必要があります

次に、ビューのxamlで、リストのItemSourceをViewModelsNotesListプロパティにバインドします

例えば

ViewModel:

public NoteViewModel : INotifyPropertyChanged
{
  //Collection must be a property
  public ObservableCollection<Note> NotesList {get; private set;}

  public NoteViewModel()
  {
     //Initialize your collection in the constructor
     NotesList = new ObservableCollection<Note>()
  }

  //.
  //.
  //.

}

必要に応じて、コードビハインドでDataContextを設定することもできます

public MainPage()
{
  this.InitializeComponent();
  NoteViewModel nvm = new NoteViewModel();
  this.DataContext = nvm;
}

または、ビューのxamlを介してDataContextを設定することもできます。ViewModelが名前空間MyProjectにあると仮定します。

名前空間への参照を追加します

<UserControl x:class=MyProject.MainPage
  xmlns:local="clr-namespace:MyProject"
  .
  .
>

ViewModelをリソースとして追加します

<UserControl.Resources>
  <local:NoteViewModel x:Key="NoteViewModel"/>
</UserControl.Resources>

メインコンテナのDataContextをこのリソースにバインドします

<Grid x:Name="LayoutRoot" DataContext="{StaticResource NoteViewModel}">

DataContextを設定したら、バインディングを介してnotesListViewコントロールのItemSourceを設定する必要があります。

ItemSource={Binding NotesList}
于 2012-11-08T05:45:49.353 に答える
1

簡単なテストケースのシナリオについては、次のことを試してください。

ViewModelを作成します。

 // Create a property as an ObservableCollection<YourType> LstItemName in your ViewModel
 // On your ViewModel constructor, create a new LstItemName instance.
 // Create a property as "YourType" ItemName to bind to the selected Item of your List

ビューを作成します。

 // Create a property of your ViewModel (codeBehind)
 // On your Views Constructor, create a new ViewModel instance. (codeBehind)
 // On loaded event of your View set the DataContext = ViewModel (codeBehind)

リストのXAML:

<List     
ItemSource={Binding LstItemName}
SelectedItem={Binding ItemName}
/>

ViewModelを使用してリストアイテムを追加することを忘れないでください。

于 2012-11-08T10:02:05.117 に答える
0

簡単なmvvmを実現するには、caliburnmicroを使用してそれを強制するライブラリを学習してみてください。セットアップが簡単で、非常に便利なコンポーネントが多数用意されています。

于 2012-11-08T05:18:26.340 に答える