views:

74

answers:

1

How do I create n-numbers of tabs with the data controls in wpf?

Let's say the main application has a button called "new customer" and "save data." When "new customer" is pressed a new tab appears with two text boxes "Name" and "Customer Number" contained in the tab, and so on. Once the two fields are populated, pressing the "save Data" should store the information from the focused tab into a database.

The problem I have is that I have a static name for the "Name" and "Customer Number" text boxes as x:Name="CustomerName" and x:Name="CustomerNumber". I found that you cannot duplicate these.

Can someone advice on how I can tackle this problem? Thank you in advance!

A: 

Using MVVM:

Have a View and a ViewModel for a New Customer, with a save button on the view, which executes code to save a Customer to the database. This code should live in a Customer model or Customer Service.

The NewCustomerView would not need to have names associated with its controls as you will be binding their Text properties to the properties on the ViewModel or an underlying model, unless you have to reference them for some other purpose than getting the data from each one.

On your main form you would have the Tab Control, with its item source set to a ObservableCollection on the MainWindowViewModel. Pressing the New Customer button would populate a new entry in to this ObservableCollection.

In the MainWindowView you would put a data template which maps the NewCustomerViewModel to the NewCustomerView, such as:

  <DataTemplate DataType="{x:Type vm:NewCustomerViewModel}">
    <AdornerDecorator>
       <views:NewCustomerView DataContext="{Binding}"/>
    </AdornerDecorator>
  </DataTemplate>

This is basically saying when the content is a NewCustomerViewModel, render a NewCustomerView.

You should go and read up on MVVM as this will solve your naming problem, as well a better architected application.

See Josh Smiths article on MVVM, there is lots of other information out there to read too.

benPearce
Thanks Ben. I will read this closely.
foureight84
If I don't undertake the MVVM design route, is there any other methods to executing this?
foureight84
You could still bind your TabControl ItemsSource to a ObservableCollection of UserControls, in your code behind when the user clicks New Customer, create a new instance of a NewCustomerUserControl and add that to the collection
benPearce