使用合成的类中的MvvmLight

我有一个源自import React,{Component} from 'react'; import Blog from './Blog' class App extends Component { render() { return ( <div classname="container"> <Blog/> </div> ); } } export default App ; 的ViewModel,它使用合成来重用其他类:

我想在合成中重用的类的简化版本:

MvvmLight.ViewModelBase

从MvvmLight ViewModelBase派生的我的ViewModel是这两个的组合:

class TimeFrameFactory
{
    public DateTime SelectedTime {get; set;}

    public ITimeFrame CreateTimeFrame() {...}
}

class GraphFactory
{
     public int GraphWidth {get; set;}

     public IGraph CreateGraph(ITimeframe timeframe) {...}
}

使用字段获取/设置有效,但是如果我想将属性设置为复合对象,则不能使用class MyViewModel : ViewModelBase { private readonly TimeFrameFactory timeFrameFactory = new TimeFrameFactory(); private readonly GraphFactory graphFactory = new GraphFactory(); private Graph graph; // standard MVVM light method to get/set a field: public Graph Graph { get => this.Graph; private set => base.Set(nameof(Graph),ref graph,value); } // this one doesn't compile: public DateTime SelectedTime { get => this.timeFrameFactory.SelectedTime; set => base.Set(nameof(SelectedTime),ref timeFrameFactory.SelectedTime,value); } // this one doesn't compile: public int GraphWidth { get => this.timeFrameFactory.GraphWidth; set => base.Set(nameof(GraphWidth),ref timeFrameFactory.GraphWidth,value); } public void CreateGraph() { ITimeFrame timeFrame = this.timeFrameFactory.CreateTimeFrame(); this.Graph = this.GraphFactory.CreateGraph(timeFrame); } }

base.Set

在属性上不允许使用引用。

我当然可以写:

set => base.Set(nameof(GraphWidth),value);

如果必须对许多属性执行此操作,则很麻烦。有没有一种整洁的方式可以做到这一点,可能类似于 public int GraphWidth { get => this.timeFrameFactory.GraphWidth; set { base.RaisePropertyChanging(nameof(GraphWidh)); base.Set(nameof(GraphWidth),value); base.RaisePropertyChanged(nameof(GraphWidh)); } }

ananhehe 回答:使用合成的类中的MvvmLight

好吧,基本方法必须能够读取(用于比较)和写入所传递的字段/属性,因此也可以引用。

由于您无法通过引用传递属性,因此我认为您被迫编写了另一种基本方法,

A)接受getter / setter委托。 (详细/烦人)

public int GraphWidth
{
    get => this.timeFrameFactory.GraphWidth;
    set => base.Set(nameof(GraphWidth),() => timeFrameFactory.GraphWidth,x => timeFrameFactory.GraphWith = x,value);
}

B)传递包含属性的Expression<Func<T>>并使用反射来提取属性并在基础中获取/设置(慢,但也可能提取名称)

public int GraphWidth
{
    get => this.timeFrameFactory.GraphWidth;
    set => base.Set(() => timeFrameFactory.GraphWidth,value);
}
本文链接:https://www.f2er.com/2631692.html

大家都在问