本系列文章導航 https://www.cnblogs.com/aierong/p/17300066.html https://github.com/aierong/WpfDemo (自我Demo地址) 希望提到的知識對您有所提示,同時歡迎交流和指正 作者:aierong出處:https://www ...
說明
CommunityToolkit.Mvvm包不提供ioc功能,但是官方建議使用:Microsoft.Extensions.DependencyInjection使用IOC
安裝
nuget:Microsoft.Extensions.DependencyInjection 包
介面和服務的定義實現
public interface IBill
{
bool IsExistId ( string name );
string GetData ( string name );
}
public class BillService : IBill
{
public string GetData ( string name )
{
return string.Format( "name:{0}" , name );
}
public bool IsExistId ( string name )
{
return name == "qq";
}
}
App.xaml.cs註冊
public partial class App : Application
{
/// <summary>
/// Gets the current <see cref="App"/> instance in use
/// </summary>
public new static App Current => ( App ) Application.Current;
/// <summary>
/// Gets the <see cref="IServiceProvider"/> instance to resolve application services.
/// </summary>
public IServiceProvider Services
{
get;
}
public App ()
{
Services = ConfigureServices();
this.InitializeComponent();
}
private static IServiceProvider ConfigureServices ()
{
var services = new ServiceCollection();
// 註冊Services
services.AddSingleton<IOCDemo.Service.Repository.IBill , IOCDemo.Service.Repository.BillService>();
services.AddSingleton<IOCDemo.Service.Service.IBill , IOCDemo.Service.Service.BillService>();
//services.AddSingleton<ISettingsService , SettingsService>();
// 註冊Viewmodels
// 不是每個Viewmodels都得來AddTransient,如果Viewmodels不需要ioc,可以不用這裡註冊
services.AddTransient<IOCDemo.ViewModels.WindowViewModel1>();
return services.BuildServiceProvider();
}
}
view中使用
原有的view與viewmodel的綁定方式改變如下:
public partial class Window1 : Window
{
public Window1 ()
{
InitializeComponent();
// this.DataContext = new WindowViewModel1(); 這樣不可以使用了,請用App.Current.Services.GetService
this.DataContext = App.Current.Services.GetService<WindowViewModel1>();
//代碼任何處,都可以使用App.Current.Services.GetService獲取到服務
//IFilesService filesService = App.Current.Services.GetService<IFilesService>();
}
}
readonly Service.Service.IBill _IBill;
public WindowViewModel1 ( Service.Service.IBill iBill )
{
this._IBill = iBill;
}
[RelayCommand( CanExecute = nameof( CanButton ) )]
void ButtonClick ()
{
//點擊按鈕,修改標題
if ( this._IBill.IsExistId( Title ) )
{
Title = "qq" + this._IBill.GetData( Title );
}
else
{
Title = "qq";
}
}
this.DataContext = App.Current.Services.GetService<WindowViewModel1>();
//代碼任何處,都可以使用App.Current.Services.GetService獲取到服務
IFilesService filesService = App.Current.Services.GetService<IFilesService>();
1
我的系列文章
A.Sql Server2005 Transact-SQL 新兵器學習 B.MCAD學習
C.代碼閱讀總結
D.ASP.NET狀態管理
E.DB(資料庫)
F.WAP
G.WinForm
H.Flex
希望上面提到的知識對您有所提示,同時歡迎交流和指正
作者:aierong
出處:http://www.cnblogs.com/aierong
貼子以"現狀"提供且沒有任何擔保,同時也沒有授予任何權利!
本文版權歸作者所有,歡迎轉載!
原創技術文章和心得,轉載註明出處!這也是對原創者的尊重!