You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ViewModel间传递参数,让View正确显示目标数据?

解决Avalonia中View显示错误ViewModel参数的问题

问题根源

你当前的代码存在两处设置ChildView DataContext的逻辑:

  1. 父ViewModel通过ViewLocator将带有正确参数的ChildViewModel实例关联到ChildView;
  2. ChildView的构造函数手动创建了另一个ChildViewModel实例并覆盖DataContext。
    后者的优先级更高,所以最终显示的是错误参数的数据。

核心解决方案

移除ChildView构造函数中手动设置DataContext的代码,让ViewLocator自动完成ViewModel与View的绑定:

修改后的ChildView.axaml.cs:

public ChildView()
{
    InitializeComponent();
    // 删除这一行:DataContext = new ChildViewModel(genericParameter: "not the parameter I want");
}

这样ViewLocator会自动将父ViewModel中UserControlContent对应的ChildViewModel实例设置为ChildView的DataContext,自然就能显示"actual parameter"了。

可选优化(针对设计时预览)

如果需要在设计器中预览ChildView,可以给ChildViewModel添加无参构造函数(或带默认参数的构造),同时保持View不手动设置DataContext:

ChildViewModel.cs示例:

public class ChildViewModel
{
    public string GenericParameter { get; }

    // 供设计时预览使用的无参构造
    public ChildViewModel() : this("design-time preview value")
    {
    }

    // 业务逻辑使用的带参构造
    public ChildViewModel(string genericParameter)
    {
        GenericParameter = genericParameter;
    }
}

这样设计器会用无参构造生成预览数据,运行时则会使用父ViewModel传递的正确实例。

内容的提问来源于stack exchange,提问作者Wind_Explorer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 02:30:45