Adding controls dynamically in WPF MVVM

If you really want to do mvvm , try to forget “how can I add controls”. You don’t have to, just think about your viewmodels – WPF create the contols for you 🙂

In your case lets say we have a SearchViewModel and a SearchEntryViewmodel.

public class SearchEntryViewmodel
{
    //Properties for Binding to Combobox and Textbox goes here
}


public class SearchViewModel 
{
    public ObservableCollection<SearchEntryViewmodel> MySearchItems {get;set;}
    public ICommand AddSearchItem {get;}
}

Till now you dont have to think about usercontrols/view. In your SearchView you create an ItemsControl and bind the ItemsSource to MySearchItems.

<ItemsControl ItemsSource="{Binding MySearchItems}"/> 

You see now all of your SearchEntryViewmodels in the ItemsControl(just the ToString() atm).

To fit your requirements to show every SearchEntryViewmodel with 3Comboboxes and so on you just have to define a DataTemplate in your Resources

<DataTemplate DataType="{x:Type local:SearchEntryViewmodel}">
    <StackPanel Orientation="Horizontal">
        <Combobox ItemsSource="{Binding MyPropertyInSearchEntryViewmodel}"/>
        <!-- the other controls with bindings -->
    </StackPanel>
</DataTemplate>

That’s all 🙂 and you never have to think about “how can I add controls dynamically?”. You just have to add new SearchEntryViewmodel to your collection.

This approach is called Viewmodel First and I think it’s the easiest way to do MVVM.

Leave a Comment

tech