Passing Parameters between xaml window and usercontrol WPF

后端 未结 3 1120
别跟我提以往
别跟我提以往 2021-02-14 04:02

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 the

相关标签:
3条回答
  • 2021-02-14 04:30

    You are passing a parameter to user control from XAML which will not work. Because if you call your user control from XAML, it is going to call the default constructor of your user control. In your case you haven't created any paramterless constructor. The other one with parameter Myusercontrol (string User) will never get called.

    The best option is to have only the paramterless constructor for your User Control and nothing more.

    public Myusercontrol()
    {
        InitializeComponent();
    }
    

    Since you are using MVVM for your user control, you should be using MVVM for the window which hosts the user control - as simple as that :)

    There you should create a property for UserControlViewModel and create its instance. If you do that it would be easier for you to bind your user control's Datacontext to its ViewModel.

    0 讨论(0)
  • 2021-02-14 04:38

    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;
              };
    }
    
    0 讨论(0)
  • 2021-02-14 04:41

    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);
    
    0 讨论(0)
提交回复
热议问题