79584128

Date: 2025-04-21 06:27:37
Score: 1.5
Natty:
Report link

You can create a markup extension to resolve ViewModel from a DI container.

Ioc.cs

public class Ioc : MarkupExtension {
    public static Func<Type, object> Resolver { get; set; }
    public Type Type { get; set; }
    public override object ProvideValue(IServiceProvider serviceProvider) => Resolver?.Invoke(Type)!;
}

App.cs:

public partial class App : Application {
    //...

    protected override void OnStartup(StartupEventArgs e) {
        //Configure the resolver so that Ioc knows how to create ViewModels
        Ioc.Resolver = (type) => type != null ? host.Services.GetRequiredService(type) : null!;
    }
}

UserContrl.XAML:

<UserControl 
             xmlns:in="clr-namespace:YourNamespaceHere"
             xmlns:vm="clr-namespace:YourNamespaceHere"
             DataContext="{in:Ioc Type={x:Type vm:MyViewModel}}" >

With this technique, you can easily resolve any ViewModel by its type in any UserControl.

Reasons:
  • RegEx Blacklisted phrase (1.5): Resolver?
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Low reputation (1):
Posted by: Alexander Russkov