Search code examples
c#wpfmahapps.metro

Communicate between two UserControl's


I'm working on some application to get more experience with WPF applications.

I manage the application frames with TabItem control of MahApps.Metro library like this:

MainWindow.xaml

<TabItem Header="Home">
    <ScrollViewer Margin="2"
        HorizontalScrollBarVisibility="Auto"
        VerticalScrollBarVisibility="Auto" Background="Transparent">
            <controlViews:HomeControl DataContext="{Binding}" />
    </ScrollViewer>
</TabItem>
<TabItem Header="Manage">
    <ScrollViewer Margin="2"
        HorizontalScrollBarVisibility="Auto"
        VerticalScrollBarVisibility="Auto">
            <controlViews:ManageControl DataContext="{Binding}" />
    </ScrollViewer>
</TabItem>

Each frame have their own class declared like this:

public partial class HomeControl : System.Windows.Controls.UserControl
{
    public HomeControl()
    {
        InitializeComponent();
    }
    // ....
}

HomeControl represent information that could change from "Manage" frame. I want to create connection between them to update if something were changed I have the ability to create selectionChange event on MainWindow and detect when user switch to "Home" tab and then update but I manage all his functionality and integration in his own class.

What options I have?


Solution

  • First of all, you don't need to Bind the Datacontext, since it inherits from it's visual parent (unless you want it otherwise). DataContext set to MainWindow -> TabControl -> Tabitem -> UserControl

    As Clemens commented, you will need a common ViewModel as part of the MVVM-pattern, whose Properties are bound to the Visuals inside your UserControl. Updating the values happens in the ViewModel (speaking of a very basic implementation), when Property changes (see: InotifyPropertyChanged)

    I made a very basic example for this, see on GitHub (It's .net Framework 4.7.2, so the project structure might differ to yours)