Ahmed Fawzy
Ahmed Fawzy

Reputation: 301

Instantiating multiple view and passing data to each one

I have a prism app where I am instantiating multiple views in the code-behind of a parent view based on a property in the viewmodel

    public I2CNavigatorView()
    {
        InitializeComponent();

        var viewModel = (I2CNavigatorViewModel) DataContext;

        for (int i = 0; i < viewModel.NumberOfI2C; i++)
        {
            var i2CTabItem = new TabItem
            {
                Header = "I2C " + i,
                Content = new I2CView(i)
            };

            NavigatorTabs.Items.Add(i2CTabItem);   
        }
    }

and I need to pass the an index to the viewmodel of each child view, so my current solution is to pass the index to the view as a parameter when instantiating the view and setting a variable in the its viewmodel

    public I2CView(int currentI2CIndex)
    {
        InitializeComponent();

        var viewModel = (I2CViewModel) DataContext;
        viewModel.CurrentI2CIndex = currentI2CIndex;
    }

but I am not quite satisfied with the solution as the data flow path is: parent view -> child view -> child viewmodel, while I need it to be: parent view -> child viewmodel

so I was thinking "Is there a way to pass the data directly to the view model when instantiating the view?"

Please advice, Thanks in advance

Upvotes: 1

Views: 51

Answers (1)

Haukinger
Haukinger

Reputation: 10863

I would start from the view model:

internal class I2CNavigatorViewModel
{
    public IReadOnlyCollection<I2CViewModel> MyItems { get; }
}

<TabControl ItemsSource="{Binding MyItems}">
    <TabControl.ContentTemplate>
        <DataTemplate>
            <I2CView />
        </DataTemplate>
    </TabControl.ContentTemplate>
</TabControl>

Then just initialize MyItems with the child view models, created with all the parameters you need.

Rant: a class doesn't want to have its name start with I, because it doesn't like to be mistaken for an interface!

Upvotes: 1

Related Questions