Brij
Brij

Reputation: 13141

How to get and remove the control at a position from the Grid

I am adding a control at run-time in a Grid using following code:

void AddControl(UserControl oControl)
{
    grid.Children.Add(oControl);
    oControl.SetValue(Grid.RowProperty, 1);
    oControl.SetValue(Grid.ColumnProperty, 0);
}

I want to remove the control at same position (row = 1, column = 0). I am not retaining reference to the control added earlier. How to get and remove the control at a position (row = 1 and column = 0) from the Grid ?

Upvotes: 0

Views: 925

Answers (1)

Fede
Fede

Reputation: 44048

I have two user controls which have some functionality in them. In the main window I have two buttons. On click of first I am setting UserControl1 in the second row and on click of second I am setting UserControl2 in the same position

What you need in order to achieve that is a TabControl:

    <TabControl>
        <TabItem Header="Tab 1">
            <Grid Background="Gray">
                <TextBlock Text="Here goes UserControl 1"
                           VerticalAlignment="Center" HorizontalAlignment="Center"/>
            </Grid>
        </TabItem>

        <TabItem Header="Tab 2">
            <Grid Background="Gray">
                <TextBlock Text="Here goes UserControl 2"
                           VerticalAlignment="Center" HorizontalAlignment="Center"/>
            </Grid>
        </TabItem>
    </TabControl>

Result:

enter image description here

Why adding controls in code behind is not good?

Because it creates a maintainability chaos. UI elements must be defined in XAML. That's what XAML is for. Creating UI elements in code behind is not only more code, it's error prone and it completely defeats the separation of UI and code that XAML enables.

What if I need to Dynamically create the UI?

Then you must use DataTemplates defined in XAML. Optionally using DataTriggers to modify the state of UI elements based on certain properties in the Model / ViewModel

WPF's idea of "dynamic" is really really different from traditional UI frameworks.

Upvotes: 3

Related Questions