Adding and Closing User Control To a Panel On WPF Window

Adding and Closing User Control To a Panel On WPF Window

In this blog I am going to explain how to use User Control in WPF. User Control can be added to any Layout Panels in WPF ,here I am adding user control to Grid Panel. To add a User control to Window or a Page, Right Click on Project=>Add=>User Control.

Image-1.jpg

Adding User Control To Grid Panel

privatevoidRectangle_Add_Click(object sender, RoutedEventArgs e)

{

    grid1.Children.Clear();//Clearing Child Elements in Grid Panel

    Rectangle_UserControlrectnagle = newRectangle_UserControl();

    grid1.Children.Add(rectnagle);

}

Initially we have to clear all the child elements in the grid panel,then we have to add the object of the User control to grid panel as shown above in code behind.
 

Closing User Control From Grid Panel:
 

privatevoidRectangle_Close_Click(objectsender,RoutedEventArgse)

{

   (this.ParentasGrid).Children.Remove(this);

}

 
To close a User control from the grid panel,the above code remove the user control nothing but the child element from the grid panel.