基于按钮单击显示和隐藏 UserControls

show and hide UserControls based on button click

我有 3 个用户控件和我的主窗口。在我的 UserControl3 中,我有两个按钮(button1 和 button2)。

  1. 我需要在启动应用程序时将 UserControl3 添加到我的 MainWindow
  2. 如果我单击 button1,usercontrol1 应该出现在我的主窗口中,如果我单击 button2,usercontrol2 应该出现在我的主窗口中。

如何做到这一点?你有这方面的例子吗?

直接从您的 MainWindow.xaml,在 window 的底部创建两个按钮,并在 window 的中心添加一个 Stack Panel

... 或者在 <Grid> 标签中复制以下 XAML 标记:

<Grid>
    <Button x:Name="UserControl1_Btn" Content="UserControl1" HorizontalAlignment="Left" Margin="10,289,0,10" Width="153"/>
    <Button x:Name="UserControl2_Btn" Content="UserControl2" Margin="354,0,10,10" Height="20" VerticalAlignment="Bottom"/>
    <StackPanel x:Name="StackPanelFixed_SP" Margin="10,10,10,47"/>
</Grid>

之后,通过右键单击项目名称,然后添加 -> 用户控件,从 解决方案资源管理器 创建 两个 用户控件。 ..(做两次)

在两个用户控件中添加一些你喜欢的内容,在这个例子中我将使用背景颜色,这样你就可以判断它是 UserControl1 还是 UserControl2

UserControl1 将被着色为 BLACK

UserControl2 将被着色为 RED

给第一个按钮添加点击事件,添加如下代码行:

    StackPanelFixed_SP.Children.Clear();
    UserControl1 UC1 = new UserControl1();
    StackPanelFixed_SP.Children.Add(UC1);
    UC1.Visibility = System.Windows.Visibility.Visible;

对于第二个按钮,添加以下代码行:

    StackPanelFixed_SP.Children.Clear();
    UserControl2 UC2 = new UserControl2();
    StackPanelFixed_SP.Children.Add(UC2);
    UC2.Visibility = System.Windows.Visibility.Visible;

最后,您将得到一个以 两个按钮(一个在左下角,另一个在右下角)和空白背景开始的程序。单击其中一个按钮后,您将看到 UI 的一部分被着色(我知道这听起来很愚蠢,但我正试图说明使用用户控件的意义)。