在xaml窗口和usercontrol WPF之间传递参数 [英] Passing Parameters between xaml window and usercontrol WPF

查看:83
本文介绍了在xaml窗口和usercontrol WPF之间传递参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将参数从xaml窗口传递给WPF用户控件构造函数?我曾尝试创建依赖项属性,但无法做到这一点.我应该尝试使用xaml扩展名还是有其他方法可以做到这一点?

How to pass Parameters from xaml window to WPF usercontrol constructor? I have tried creating dependency property, but it fails to do it. Should I try xaml extensions or is there any other way to do it?

<local:Myusercontrol Param1="user1"/>

调用 Window

xaml.cs以及其用户控件.

xaml.cs of the calling Window, well its usercontrol.

public partial class SomeView : UserControl
{
    SomeViewModel vm = new SomeViewModel();
    public SomeView()
    {
        this.DataContext = vm;
        InitializeComponent;
    }
}

上面窗口的

InitializeComponent 在创建用户控件的实例之前清除通过xaml设置的依赖项属性的值,因此depencency属性的值始终为空.

InitializeComponent of above window clears value of dependency property set through xaml before creating an instance of the user control and hence value of depencency property is always null.

和用户控件的xaml.cs

and usercontrol's xaml.cs

Myusercontrol : UserControl
{
  public Myusercontrol (string User)
  {
    InitializeComponent();
    UserControlViewModel vm = new UserControlViewModel (User);
    this.DataContext = vm;
  }

请注意,我正在使用MVVM模式.

Note that I am using MVVM pattern.

推荐答案

XAML不能将构造函数与参数一起使用.保留您尝试使用的依赖项属性:

XAML can't use constructor with parameter. Keep what you've tried with dependency property :

<local:Myusercontrol Param1="user1"/>

然后您可以在构造函数中尝试使用此方法:

then you can try this in constructor :

public Myusercontrol()
{
    InitializeComponent();
    Loaded += (sender, args) =>
          {
                UserControlViewModel vm = new UserControlViewModel(Param1);
                this.DataContext = vm;
          };
}

这篇关于在xaml窗口和usercontrol WPF之间传递参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆