Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Parameters between xaml window and usercontrol WPF

Tags:

c#

.net

mvvm

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"/>

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 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.

and usercontrol's xaml.cs

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

Note that I am using MVVM pattern.

like image 745
user2330678 Avatar asked Feb 12 '14 02:02

user2330678


2 Answers

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;
          };
}
like image 90
har07 Avatar answered Sep 28 '22 11:09

har07


If your user control will be used at many places, i recommend har07 answer and use dependency property. But if your control will be used just once or two times and you're lazy enough to create a dependency property, you can always create your control from code. For example create a grid as parent and insert your control as child of your grid

XAML

<Grid Name="Wrapper"></Grid>

Code

MyUserControl userControl = new MyUserControl(param);
Wrapper.Children.Add(userControl);
like image 38
euclid135 Avatar answered Sep 28 '22 10:09

euclid135