Adding controls dynamically in WPF MVVM

前端 未结 3 482
日久生厌
日久生厌 2020-11-28 06:06

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?

3条回答
  •  臣服心动
    2020-11-28 06:46

    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 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.

     
    

    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

    
        
            
            
        
    
    

    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.

提交回复
热议问题