CommunityToolkit.Mvvm未内置IOC,可以使用Microsoft.Extensions.DependencyInjection.
在App中注册ViewModel和其他服务
public partial class App : Application
{
public App()
{
Services = ConfigureServices();
this.InitializeComponent();
}
public new static App Current => (App)Application.Current;
public IServiceProvider Services { get; }
private IServiceProvider ConfigureServices()
{
var sc = new ServiceCollection();
// 注册所有的ViewModel
sc.AddSingleton(new ProductViewModel() { ModelName = "HP"});
// 注册其他服务
sc.AddSingleton<IService,ImplementationService>());
return sc.BuildServiceProvider();
}
}
在View中,获取ViewModel实例赋值给DataContext
/// <summary>
/// ProductView.xaml 的交互逻辑
/// </summary>
public partial class ProductView : Window
{
public ProductView()
{
InitializeComponent();
App.Current.Services.GetService<ProductViewModel>()!.ModelName = "DELL";
this.DataContext = App.Current.Services.GetService<ProductViewModel>();
}
}
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/280648.html