Search code examples
wpfdatagrid

Different ItemsSource to each user control


In my window I have ListBox that contain collection of usercontrols like:

<ListBox ItemsSource="{Binding UserControls}">

Inside the user control class I have DataGrid that bind to datatable:

<DataGrid ItemsSource="{Binding TableResult}"/>

From the window's viewmodel I'm adding dynamiclly more usercontrols to the ListBox, like:

void AddUserControl()
{
   MyUserControl uc = new MyUserControl
   {
     DataContext = this
   };
   UserControls.Add(uc);
}

For now all the usercontrols bind to the same table: TableResult

But what I what is a new DataTable for each usercontrol.

I have tried like:

void AddUserControl()
{
   MyUserControl uc = new MyUserControl
   {
     DataContext = this
   };
   DataTable dt = new DataTable();
   uc.MyGridView.ItemsSource = dt.DefaultView;
   UserControls.Add(uc);
}

but now this part will be missing for the new datatable:

DataTable dt;
public DataTable Dt
{
    get { return dt; }
    set
    {
        dt = value;
        RaisePropertyChanged("Dt");
     }
}

Note: I have only one viewmodel for the window, therefore the datacontext of each usercontrol is the same viewmodel

Any suggestions for this secnario? I mean how do I bind a new datatable for each new usercontrol


Solution

  • You shouldn't bind to an IEnumerable<UserControl>. Referencing UI elements or controls in a view model breaks the MVVM pattern.

    What you should do is to create a class to which you add the DataTable property and then bind to an IEnumerable<YourClass>. The actual UserControl should be defined in the ItemTemplate of the ListBox in the view:

    <ListBox ItemsSource="{Binding DataObjects}">
        <ListBox.ItemTemplate>
            <local:MyUserControl  />
        </ListBox.ItemTemplate>
    </ListBox>
    

    The root element in the ItemTemplate inherits its DataContext from the current item in the ListBox which means that you can bind directly to any public property of YourClass in MyUserControl:

    <DataGrid ItemsSource="{Binding TableProperty}"/>