Home > Enterprise >  WPF Pass object from window's Usercontrol to another window's Usercontrol
WPF Pass object from window's Usercontrol to another window's Usercontrol

Time:09-21

I have 2 windows and 2 user controls the first window uses the first user control to display brief info about objects in a listview, now when the user clicks on an object(row) from the list the second window should open with the second user control showing the full info of that object.

So the problem is how I can pass that object from UC1 to UC2.

CodePudding user response:

The answer to your problem is to use MVVM. For example:

List Window:

<Window>
    <ItemsControl ItemSource = {Binding DataItems}>
        <ItemsControl.ItemTemplate>
            <userControls:YourLessDetailedUserControl/>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</Window>

Detail Window:

<Window>
         <userControls:YourMoreDetailedUserControl DataContext = {Binding DataItem}/>
</Window>

ViewModels:

class MainWindowViewModel
{
     public List<DataItemViewModel> DataItems {get;}
}

class DataItemViewModel
{
     public ICommand OpenInDetailedWindow {get;}

     //more properties here to describe your data item
}

class DetailedWindowViewModel
{
    DataItemViewModel DataItem {get;}
}

The ICommand in the DataItemViewModel should be defined to open the Detail Window with DetailedWindowViewModel.DataItem set to that DataItemViewModel.

If you are new to MVVM this will all look pretty foreign. That's ok though! It's hard for everyone at first.

  • Related