canton7 / Stylet

A very lightweight but powerful ViewModel-First MVVM framework for WPF for .NET Framework and .NET Core, inspired by Caliburn.Micro.
MIT License
988 stars 143 forks source link

Creating a factory with runtime data as parameter #128

Closed daawaan4U closed 4 years ago

daawaan4U commented 4 years ago

I'm stuck in creating a SubViewModel from a factory and passing a runtime data as a parameter.

My ViewModel currently looks like this:

public class ItemBrowserViewModel : MainPageBase
{
    private uint data = 0;
    public uint data
    {
        get => data;
        set => SetAndNotify(ref data, value);
    }

    private Func<uint, ItemEditorViewModel> ItemEditorViewModelFactory { get; }

    public ICommand OpenEditorCommand = new RelayCommand<object>((_) => 
        NavigationService.Open(ItemEditorViewModelFactory(data))
    );

    public ItemBrowserViewModel(NavigationService navigationService, 
                         Func<uint, ItemEditorViewModel> itemEditorViewModelFactory)
                         : base (navigationService) 
    {
        ItemEditorViewModelFactory = itemEditorViewModelFactory;
    }
}


My SubViewModel:

public class EditorViewModel : PageBase
{
    private uint passedValue = 0;
    public uint PassedValue
    {
        get => passedValue;
        set => SetAndNotify(ref passedValue, value);
    }

    public EditorViewModel(NavigationService navigationService, uint value)
        : base(navigationService)
    {
        PassedValue = value;
    }
}


Apparently, I do not know how to configure the IoC for this. My attempts were always like this:

builder.Bind<Func<uint, EditorViewModel>>().ToFactory((value, container) => {
    // . . .  Can't think of anything that would work in here
});


I found a similar issue from here that also passes a runtime data to the factory but he/she constructed another class instead. Is it possible to solve this just by using a Func?

canton7 commented 4 years ago

No, there's nothing built into the ioc container which supports this. Larger ioc contains often have support for this. I normally write my own factory types for these cases.

daawaan4U commented 4 years ago

Thank you for the response!