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.