代码之家  ›  专栏  ›  技术社区  ›  Maximus

如何共享属性?

  •  0
  • Maximus  · 技术社区  · 7 年前

    我有一个问题,两个派生视图模型之间共享了一个属性:

    public abstract class MyBaseViewModel : ViewModelBase
    {
        private string _sharedProperty;
        public string SharedProperty
        {
            get => _sharedProperty;
            set => this.RaiseAndSetIfChanged(ref _sharedProperty, value);
        }
    }
    
    public abstract class ViewModelA : MyBaseViewModel
    {
    
    }
    
    public abstract class ViewModelB : MyBaseViewModel
    {
    
    }
    
    public sealed partial class FirstPage : IViewFor<ViewModelA>
    {
        this.Bind(ViewModel,
            vm => vm.SharedProperty,
            view => view.MycontrolA.Text)
        .DisposeWith(disposable);
    }
    
    public sealed partial class SecondPage : IViewFor<ViewModelB>
    {
        this.Bind(ViewModel,
            vm => vm.SharedProperty,
            view => view.MycontrolB.Text)
        .DisposeWith(disposable);
    }
    

    当我更新时 股份所有权 第二页 ,绑定 第一页 未更新。现在很明显每个ViewModel都有它自己的属性实例,因为它不是 静止的 . 自从 RAISE和ETIFCHANGED 需要一个实例来执行,我们如何才能拥有一个绑定在两个不同视图中的属性并共享其绑定??

    1 回复  |  直到 7 年前
        1
  •  2
  •   Glenn Watson    7 年前

    考虑使用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机制。

    推荐文章