我有一个从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) {...}
}
从MvvmLight ViewModelBase派生的My ViewModel是这两个的组合:
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), ref timeFrameFactory.GraphWidth, value);
属性上不允许使用ref。
我当然可以写:
public int GraphWidth
{
get => this.timeFrameFactory.GraphWidth;
set
{
base.RaisePropertyChanging(nameof(GraphWidh));
base.Set(nameof(GraphWidth), ref timeFrameFactory.GraphWidth, value);
base.RaisePropertyChanged(nameof(GraphWidh));
}
}
如果您要对许多属性进行此操作,则很麻烦。有没有一种整洁的方法可以执行此操作,可能类似于ObservableObject.Set
?
嗯,基本方法必须能够读取(用于比较)和写入所传递的字段/属性,因此需要引用。
由于您无法通过引用传递属性,我认为您被迫编写了另一种可以使用的基本方法
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);
}