Splat.Locator 一个 ViewModel 的多个视图
Splat.Locator Multiple views for one ViewModel
我使用下面的代码
Splat.Locator.Current.GetService(...)
获取视图模型的视图。但是这种方法只允许对一个视图模型使用一个视图。但我必须在多个视图中显示 1 个数据(视图模型)。 Splat.Locator可以吗?
我认为这是不可能的,因为当您首先使用 ViewModel 进行导航时,Locator 会感到困惑,因此它始终会实例化与 ViewModel 关联的最新视图。我的建议是您可以创建该 ViewModel 作为基础 class 并创建另一个继承该 ViewModel 的 ViewModel,然后像往常一样在 Splat.Locator 中分配它
Register() 和 GetService() 有一个契约参数,您可以将其用作获取所需实现的关键。
示例,其中 "giveMeBar"/"giveMeBaz" 是合约参数的值:
using System;
using Splat;
namespace ConsoleApp1
{
internal class Program
{
private static void Main()
{
// Register
Locator.CurrentMutable.Register(() => new Bar(), typeof(IFoo), "giveMeBar");
Locator.CurrentMutable.Register(() => new Baz(), typeof(IFoo), "giveMeBaz");
// Resolve
var bar = Locator.Current.GetService<IFoo>("giveMeBar");
var baz = Locator.Current.GetService<IFoo>("giveMeBaz");
// Which types did we get?
Console.WriteLine(bar);
Console.WriteLine(baz);
Console.ReadLine();
// Outputs:
// ConsoleApp1.Bar
// ConsoleApp1.Baz
}
}
internal interface IFoo { }
internal class Bar : IFoo { }
internal class Baz : IFoo { }
}
我使用下面的代码
Splat.Locator.Current.GetService(...)
获取视图模型的视图。但是这种方法只允许对一个视图模型使用一个视图。但我必须在多个视图中显示 1 个数据(视图模型)。 Splat.Locator可以吗?
我认为这是不可能的,因为当您首先使用 ViewModel 进行导航时,Locator 会感到困惑,因此它始终会实例化与 ViewModel 关联的最新视图。我的建议是您可以创建该 ViewModel 作为基础 class 并创建另一个继承该 ViewModel 的 ViewModel,然后像往常一样在 Splat.Locator 中分配它
Register() 和 GetService() 有一个契约参数,您可以将其用作获取所需实现的关键。
示例,其中 "giveMeBar"/"giveMeBaz" 是合约参数的值:
using System;
using Splat;
namespace ConsoleApp1
{
internal class Program
{
private static void Main()
{
// Register
Locator.CurrentMutable.Register(() => new Bar(), typeof(IFoo), "giveMeBar");
Locator.CurrentMutable.Register(() => new Baz(), typeof(IFoo), "giveMeBaz");
// Resolve
var bar = Locator.Current.GetService<IFoo>("giveMeBar");
var baz = Locator.Current.GetService<IFoo>("giveMeBaz");
// Which types did we get?
Console.WriteLine(bar);
Console.WriteLine(baz);
Console.ReadLine();
// Outputs:
// ConsoleApp1.Bar
// ConsoleApp1.Baz
}
}
internal interface IFoo { }
internal class Bar : IFoo { }
internal class Baz : IFoo { }
}