Search code examples
c#wpfxamluser-controls

how to modify the host window from a user control?


i'm coding a c# application using WPF

i have a main Window which contain a Grid named " SelectionGrid ". this grid will contain Control User, my problem is that i want to modify ( add/delete) Control User in that grid from a USER CONTROL itself

for example: SelectionGrid host the User Control " Menu" in this menu there a button, i want from this button to remove the Menu User Control and add another User Control in this SelectionGrid

main window code :

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        UserControl usc = new Menu();
        SelectionGrid.Children.Add(usc);
    }}

Menu User Control code :

public partial class Menu : UserControl
{
    public Menu()
    {   
        InitializeComponent();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        // want to add Another User Control in SelectionGrid
    }

Solution

  • Firstly,put your userControl in some container control like Grid.Then you can easily access and modify the grid from the usercontrol as follows:

     var parent = (Grid)this.Parent;
     ///do what you want to do with parent
    

    A bit of knowledge-sharing : The below code can be used to access the parent of controls like Page,UserControl :

    public static T FindParent(DependencyObject child)
    {
    DependencyObject parentObject = VisualTreeHelper.GetParent(child);
    if (parentObject == null)
        return null;
    T parent = parentObject as T;
    if (parent != null)
        return parent;
    else
        return FindParent<T>(parentObject);
    }
    
    private void test()
    {
      ControlTypeHere parent = FindParent<ControlTypeHere>(this);
    

    Hope this helps :)