c# - WPF 在代码后面初始化对象并在 View 模型中使用该对象

标签 c# wpf xaml mvvm

我需要在后面的 xaml.cs 代码中初始化对象,然后在绑定(bind)的 View 模型中使用该对象。但是当我这样做时,对象会正确初始化,但 viewmodel 的行为就像它仍然为空一样。

MainWindow.xaml

<oxys:PlotView x:Name="dataPlot" Model="{Binding DataPlotModel}" Margin="10,10,185,39"/>

MainWindow.xaml.cs
MainWindowViewModel viewModel;

public MainWindow()
{
    viewModel = new MainWindowViewModel();
    DataContext = viewModel;

    InitializeComponent();

    PlotModel DataPlotModel = new PlotModel();
    dataPlot.Model = DataPlotModel;
}

MainWindowViewModel.cs
public PlotModel DataPlotModel { get; set; }

DataPlotModel在 viewmodel 中始终为空,除非我在 viewmodel 中严格初始化它。

最佳答案

您需要设置 DataPlotModel某处 View 模型的属性:

MainWindowViewModel viewModel;

public MainWindow()
{
    viewModel = new MainWindowViewModel();
    DataContext = viewModel;

    InitializeComponent();

    viewModel.DataPlotModel = new PlotModel(); //<-- Set the view model property
}

您应该设置 View 模型属性,而不是直接设置控件的属性,因为这会破坏绑定(bind)。

关于c# - WPF 在代码后面初始化对象并在 View 模型中使用该对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45588224/

相关文章:

c# - 将一种语言的语音转换为另一种语言

c# - 接口(interface)从 vb.net 到 c# 的转换

c# - 未找到 WPF PresenterFramework.Aero2

wpf - 运行时如何处理 XAML 命名空间?

wpf - 确保实现 WPF 任务栏窗口预览

c# - 使用 Type 变量转换变量

c# - 使用 IMiddleware 时添加自定义中间件不起作用

c# - 如何将图像放置在其中心而不是左上角?

c# - 删除 xaml 文件中未使用的引用程序集

c# - stackpanel 中动态添加的控件在 wpf c# 中不可见