Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
580 views
in Technique[技术] by (71.8m points)

Adding controls dynamically in WPF MVVM

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...