Question

Goal:
Reduce tight coupling and increase loose coupling for user control 1 and 2.

Problem:
Is it possible to send some instance from main windows to user control 1 and 2?
If yes, do you have a example or recommended link about it?

Information:
- I'm using VS 2013

enter image description here

Xaml code:

<Window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:usercontrol_menu="clr-namespace:usercontrol_menu;assembly=usercontrol_menu" xmlns:usercontrol_kassa="clr-namespace:usercontrol_kassa;assembly=usercontrol_kassa" x:Class="main_system.MainWindow"
        Title="MainWindow" Height="900" Width="1300         ">
    <Grid>
        <Frame x:Name="mainFrame"/>
        <ContentControl x:Name="cc_content" Content="ContentControl" HorizontalAlignment="Left" Margin="482,144,-228,0" VerticalAlignment="Top" Height="298" Width="1038"/>
        <usercontrol_menu:UserControl1 HorizontalAlignment="Left" VerticalAlignment="Top"/>
        <usercontrol_kassa:UserControl1 HorizontalAlignment="Left" Margin="10,344,0,0" VerticalAlignment="Top"/>
    </Grid>
</Window>
Was it helpful?

Solution

Pass a reference in the ctor

namespace UserControlPassReference
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            UserControl1 uc1 = new UserControl1(this);
        }
    }
}

namespace UserControlPassReference
{
    public partial class UserControl1 : UserControl
    {
        private Window main;
        public UserControl1()
        {
            InitializeComponent();
        }
        public UserControl1(Window Main)
        {
            InitializeComponent();
            main = Main;
        }
    }
}

OTHER TIPS

Consider using the Window.GetWindow Method.

http://msdn.microsoft.com/en-us/library/system.windows.window.getwindow(v=vs.110).aspx

var wnd = Window.GetWindow(this); //Assuming this is a user control (or any DependencyObject).

Look here

You also can be interested in PRISM

So, once you have IoC container, you can pass it to all your UserControls (via ViewModels, or something else), and using it you can get access to anything you have registered in it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top