nan
nan

Reputation: 585

Passing data between user controls in wpf

I have a user control with a button which when clicked opens a new user control.

private void Button_Click(object sender, RoutedEventArgs e)
    {
        Window window = new Window
        {
            Title = "Window2",
            Content = new UserDataControl2()
        };
        window.ShowDialog();

    }

I need to pass a collection to the new user control. How can I do it?

Upvotes: 1

Views: 7514

Answers (2)

soydachi
soydachi

Reputation: 901

The best way is passing object to DataContext of this Window. For this you will need to create a class where store this parameters (ViewModels) and after "binding" to the Window (View). After you can pass this object assigning to Datacontext.

Look to MVVM model to understand better what I mean.

MVVM Pattern Made Simple

MVVM in Depth

Upvotes: 1

Inisheer
Inisheer

Reputation: 20794

The easiest way is to create a custom constructor for your user control.

// Button_Click event
Window window = new Window
{
     Title = "Window2",
     Content = new UserDataControl2("My Data");
};


// User Control class.
string _info;

public UserDataControl2(string info)
{
   _info = info.
};

You could also create a method or property in the user control to receive the data as well. Use whichever seems more appropriate in your context.

Upvotes: 2

Related Questions