我有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; }
}
}
最佳答案
在不起作用的情况下,您未设置类型PlotModel
的实例的属性Data
,而只是将方法参数PlotModel
的值设置为新的PlotModel
实例。请注意,Data.PlotModel
仍为空。
这行在这里:
public virtual void Draw(PlotModel PlotModel)
{
PlotModel = new OxyPlot.PlotModel(); //do not Working
将新实例分配给方法
PlotModel
的参数Draw
,而不是实例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()