我有ObservableCollection女巫可以拥有两种不同的类型FirstDerivedType
和SecondDerivedType
。他们都在Data
上有参考。主要问题是当我在构造函数PlotModel
中创建FirstDerivedType()
的实例时
Data.PlotModel = new PlotModel();
效果很好。但是当我在PlotModel
中创建base.Draw(Data.PlotModel);
的实例时,我会在null
中获得DataContext
。为什么呢?
namespace WpfApplication3
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new CurrentViewModel();
}
}
public class CurrentViewModel
{
private ObservableCollection<BaseType> items;
public ObservableCollection<BaseType> Items
{
get
{
return this.items;
}
set
{
this.items = value;
}
}
public CurrentViewModel()
{
Items = new ObservableCollection<BaseType>();
Items.Add(new FirstDerivedType (17));
Items.Add(new FirstDerivedType (100));
Items.Add(new FirstDerivedType (50));
Items.Add(new FirstDerivedType (120));
}
}
public class Data:INotifyPropertyChanged
{
public int ID { get; set; }
public PlotModel PlotModel { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string info)
{
if (PropertyChanged!=null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
}
public abstract class BaseType
{
public virtual void Draw(PlotModel PlotModel)
{
PlotModel = new OxyPlot.PlotModel(); //do not Working
LineSeries LS= new LineSeries();
Random rnd = new Random();
for (int i=0; i<10; i++)
{
LS.Points.Add(new DataPoint(i,rnd.Next(1,100)));
}
PlotModel.Series.Add(LS);
PlotModel.InvalidatePlot(false);
}
}
public class FirstDerivedType : BaseType
{
public FirstDerivedType(int ID)
{
Data = new Data();
//Data.PlotModel = new PlotModel(); //Working
Data.ID = ID;
base.Draw(Data.PlotModel);
}
public Data Data { get; set; }
}
public class SecondDerivedType : BaseType
{
public Data Data { get; set; }
}
}
答案 0 :(得分:2)
如果不能正常工作,则表示您没有设置PlotModel
类型实例的属性Data
,只需将方法参数PlotModel
的值设置为PlotModel
的新实例。请注意,Data.PlotModel
仍然为空。
这一行:
public virtual void Draw(PlotModel PlotModel)
{
PlotModel = new OxyPlot.PlotModel(); //do not Working
将新实例分配给方法PlotModel
的参数Draw
, NOT 实例PlotModel
的属性Data
。它不会影响保存属性Data
的实例PlotModel
。这一行:
base.Draw(Data.PlotModel);
如果在Data.PlotModel
方法中重新分配方法参数,将不会导致属性Draw
发生变化。
尝试将Draw
重命名为CreatePlotModel
,然后执行以下操作:
public virtual PlotModel CreatePlotModel()
{
var model = new OxyPlot.PlotModel();
LineSeries LS= new LineSeries();
Random rnd = new Random();
for (int i=0; i<10; i++)
{
LS.Points.Add(new DataPoint(i,rnd.Next(1,100)));
}
model.Series.Add(LS);
model.InvalidatePlot(false);
return model;
}
然后分配数据的PlotModel
属性:Data.PlotModel = base.CreatePlotModel()
答案 1 :(得分:1)
从构造函数调用虚方法很危险。 请参阅https://msdn.microsoft.com/en-us/library/s8e39b8h(v=vs.120).aspx
中的详细信息