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

WPF中无需手动设置DataContext如何实现窗口间SelectedUser传递

方案:给UserInfoWindow添加专属依赖属性传递参数

你可以通过给UserInfoWindow新增一个User类型的依赖属性,在属性变更回调中读取窗口资源中已初始化的UserInfoWindowController实例完成赋值,完全符合你的限制要求。

步骤1:修改UserInfoWindow后台代码

在UserInfoWindow.xaml.cs中添加如下代码:

public partial class UserInfoWindow : Window
{
    // 注册User依赖属性
    public static readonly DependencyProperty UserProperty = DependencyProperty.Register(
        nameof(User),
        typeof(User),
        typeof(UserInfoWindow),
        new PropertyMetadata(default(User), OnUserPropertyChanged));

    public User User
    {
        get => (User)GetValue(UserProperty);
        set => SetValue(UserProperty, value);
    }

    // 依赖属性变更回调
    private static void OnUserPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (d is not UserInfoWindow window) return;
        // 直接读取XAML中定义的Controller资源实例,无需手动创建
        if (window.Resources["Controller"] is UserInfoWindowController controller)
        {
            controller.User = e.NewValue as User;
        }
    }

    public UserInfoWindow()
    {
        InitializeComponent();
    }
}

步骤2:修改MainWindowController中窗口创建逻辑

只需在创建UserInfoWindow时给新增的依赖属性赋值即可:

private void DisplaySelectedUserInfoCommandHandler()
{
    if (SelectedUser == null) return;
    // 无需修改DataContext、无需传入Controller实例
    _ = new UserInfoWindow { User = SelectedUser }.ShowDialog();
}

方案原理说明

  1. C#对象初始化器的执行顺序为:先执行构造函数(内部会调用InitializeComponent加载XAML资源,此时UserInfoWindowController已经在资源中初始化完成),再给属性赋值,因此回调中读取资源中的Controller不会为空。
  2. 全程没有手动创建UserInfoWindowController实例传入,也没有修改窗口的DataContext,完全符合限制条件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 17:36:04