[英]WPF initialize object in code behind and use that object in viewmodel
I need to initialize object in xaml.cs code behind and then use that object in my binded viewmodel. 我需要在xaml.cs代码后面初始化对象,然后在绑定的viewmodel中使用该对象。 But when I do that the object properly initialize, but viewmodel acts like it's still null.
但是,当我这样做时,对象会正确初始化,但是viewmodel的行为就像它仍然为null。
MainWindow.xaml MainWindow.xaml
<oxys:PlotView x:Name="dataPlot" Model="{Binding DataPlotModel}" Margin="10,10,185,39"/>
MainWindow.xaml.cs MainWindow.xaml.cs
MainWindowViewModel viewModel;
public MainWindow()
{
viewModel = new MainWindowViewModel();
DataContext = viewModel;
InitializeComponent();
PlotModel DataPlotModel = new PlotModel();
dataPlot.Model = DataPlotModel;
}
MainWindowViewModel.cs MainWindowViewModel.cs
public PlotModel DataPlotModel { get; set; }
And the DataPlotModel
in viewmodel is always null unless I initialize it strictly in viewmodel. 除非我在viewmodel中严格初始化它,否则
DataPlotModel
中的DataPlotModel
始终为null。
You need to set the DataPlotModel
property of the view model somewhere: 您需要在某处设置视图模型的
DataPlotModel
属性:
MainWindowViewModel viewModel;
public MainWindow()
{
viewModel = new MainWindowViewModel();
DataContext = viewModel;
InitializeComponent();
viewModel.DataPlotModel = new PlotModel(); //<-- Set the view model property
}
You should set the view model property rather than setting the property of control directly as this will break the binding. 您应该设置视图模型属性,而不是直接设置控件的属性,因为这会破坏绑定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.