gpt4 book ai didi

c# - 使用合成的类中的MvvmLight

转载 作者:行者123 更新时间:2023-12-03 10:17:21 25 4
gpt4 key购买 nike

我有一个从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);
}

关于c# - 使用合成的类中的MvvmLight,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60724365/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com