简体   繁体   中英

Looking for guidance for where to put some code in a WPF MVVM application

First time attempting MVVM, looking for clarity on where to put some code.

My main view will need to bind to a list that will be holding 1 to many UserControls.

Would the List exist in the ViewModel or the Model? From what I'm reading, the model contains properties typically that the View binds to via the ViewModel. I don't see how that would work for this, the Model would not need to know about the List of UserControls which is a list of a View(UserControl), I may be making this harder than needed, but I'm still wrapping my mind around where code should be placed and I want to understand it. Thanks for any guidance, or if I did not explain myself well please let me know.

Your UserControls should have a ViewModel (Let's call it ItemViewModel by now).

Your MainViewModel should have an ObservableCollection<ItemViewModel> .

Then your view should have an ItemsControl (or one of its derivatives such as ListBox ) for which the ItemsSource property will be bound to the ObservableCollection . And then the ItemsControl should define an ItemTemplate that contains your UserControl .

This is the right way to do what you're describing with WPF / MVVM.

Example (pseudocode):

MainViewModel:

public class MainViewModel
{
    public ObservableCollection<ItemViewModel> Items {get;set;}
}

MainView:

<Window>
   <ItemsControl ItemsSource="{Binding Items}">
       <ItemsControl.ItemTemplate>
          <DataTemplate>
             <my:UserControl/>
          </DataTemplate>
       </ItemsControl.ItemTemplate>
   </ItemsControl>
</Window>

Keep in mind that each instance of UserControl will have it's DataContext set to the corresponding item in the source collection.

Therefore, if your ItemsViewModel looks something like this:

public class ItemsViewModel
{
    public string LastName {get;set;} 
    public string FirstName {get;set;} 
    //INotifyPropertyChanged, etc.
}

your UserControl can be defined like this:

<UserControl>
   <StackPanel>
      <TextBox Text="{Binding LastName}"/>
      <TextBox Text="{Binding FirstName}"/>
   </StackPanel>
</UserControl>

You shouldn't need a list of UserControls. What you would likely have is your View binding to a List of items in your ViewModel. For example, create a ListBox and set it's ItemsSource to your ViewModel's list.

To create a your user control for each item, you would need to create a DataTemplate for the type in your list and specify your UserControl and you can give any bindings inside that usercontrol to the item.

The ListBox will then use the DataTemplate to create a UserControl for each item in the list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM