考虑使用DependencyInjection和某种注册的常量值来存储两个对象之间的注册。然后使用ObservablesPropertyHealper更新您的属性。
在Splat DI中注册
private static void RegisterDynamic(IMutableDependencyResolver resolver)
{
resolver.RegisterConstant<IMyDataType>(new MyDataType());
}
然后在ViewModels构造函数中可以
public class ViewModelA : IDisposable
{
private readonly ObservableAsPropertyHelper<string> sharedProperty;
private readonly IMyDataType dataType;
public ViewModelA(IMyDataType dataType = null)
{
this.dataType = dataType ?? Locator.Current.GetService<IMyDataType>();
this.sharedProperty = dataType.WhenAnyValue(x => x.SharedProperty).ToProperty(this, x => x.SharedProperty);
}
public string SharedProperty => this.sharedProperty.Value;
public void Dispose() => this.sharedProperty?.Dispose();
}
然后可以对ViewModelB重复相同的过程。
您需要考虑的另一个问题是,您可能希望处理ToProperty()的订阅。在上面的例子中,我刚刚做了一个简单的处理,还可以使用WhenActivate机制。