简体   繁体   中英

how to add WPFUserControl to a StackPanel depending on condition in C# WPF

I have a StackPanel in a WPF Form. And I do have 3 different WPF User Control that I need to load inside the panel depending on the condition. Any Ideas, I know it should be done in the behind code, tried to add the usercontrol to the stackPanel I was not able too find the add method. Do I need to user different control than the stack panel to do that?

<StackPanel Panel.ZIndex="1" x:Name="pnlRightMenu" Orientation="Horizontal" HorizontalAlignment="Right" Margin="0,403,-576,342" Grid.Column="1" Width="576" VerticalAlignment="Center">
    <Border BorderBrush="Transparent" BorderThickness="1" Width="550" Background="#4C808080" Margin="0,-163,0,-126" >
        <Grid>
            <Button x:Name="btnRightMenuHide" Click="btnRightMenuHide_Click" Content="&gt;&gt;" Margin="-16,-191,0,0" FontSize="10" RenderTransformOrigin="-1.338,2.571" VerticalAlignment="Top" HorizontalAlignment="Left" Visibility="Hidden"/>
        </Grid>
    </Border>
</StackPanel>

您可以将任何UIElement添加到StackPanelChildren集合中:

pnlRightMenu.Children.Add(new UserControl1());

In your button click event handler you'll want to switch through the conditions.

Use the switch to append a new instance of the user control to the StackPanel's Children collection:

private void btnRightMenuHide_Click(object sender, RoutedEventArgs e)
{
    switch (condition)
    {
        case "case 1":
            UserControl1 uc1 = new UserControl1();
            pnlRightMenu.Children.Add(uc1);
            break;
        case "case 2":
            UserControl2 uc2 = new UserControl2();
            pnlRightMenu.Children.Add(uc2);
            break;
        case "case 3":
            UserControl3 uc3 = new UserControl3();
            pnlRightMenu.Children.Add(uc3);
            break;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM