Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding controls dynamically in WPF MVVM

Tags:

wpf

mvvm-light

I am working on a dynamic search view wherein clicking a button should add a new row containing 3 combobox and 2 textboxes.

How should I go about doing this?

like image 536
spiritqueen Avatar asked Jun 19 '12 05:06

spiritqueen


1 Answers

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.

like image 159
blindmeis Avatar answered Oct 24 '22 08:10

blindmeis