一、修改App.xaml
删除启动的Uri(StartupUri=“MainWindow.xaml”)
二、修改App.xaml.cs
1、集成Microsoft.Extensions.DependencyInjection 2、重写OnStartUp方法
var services = new ServiceCollection();
services.AddSingleton<MainWindow>();
services.AddSingleton<UserControl1>();
services.AddTransient<ITest, Test>();
var serviceProvider = services.BuildServiceProvider();
var window = serviceProvider.GetRequiredService<MainWindow>();
window.Show();
三、ITest、Test添加Display方法
public class Test : ITest
{
public void Display()
{
MessageBox.Show("Test展示");
}
}
四、MainWindow.xaml.cs
public partial class MainWindow : Window
{
private readonly UserControl1 _userControl1;
public MainWindow(UserControl1 userControl1)
{
_userControl1 = userControl1;
InitializeComponent();
}
private void MainWindow_OnInitialized(object? sender, EventArgs e)
{
TestControl.Children.Add(_userControl1);
}
}
五、UserControl1.cs
public partial class UserControl1 : UserControl
{
private readonly ITest _test;
public UserControl1(ITest test)
{
_test = test;
InitializeComponent();
}
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
_test.Display();
}
}
六、运行结果
|