【解決方法】同じスタックパネルでusercontrol1を閉じてusercontrol2を開く方法は?


初めてボタンをクリックすると、usercontrol1 が開きますが、2 番目のボタンをクリックすると、usercontrol2 は開きません (usercontrol2 は開きますが、form1 は非表示にならないため、form2 は表示されません)。 Form1 と Form2 の両方を同じパネルで開く

私が試したこと:

C#
userControl1.Visibility = Visibility.Collapsed;
userControl2.Visibility = Visibility.Visible;

UserControl1 newFormControl = new UserControl1();
settingpanel.Children.Add(newFormControl);

解決策 1

コード ビハインド バージョンを次に示します。

1. UI/XAML

XML
<Window x:Class="WpfControlHost.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="450" Width="800" >

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition />
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <ContentControl x:Name="ContentControl" />
        <Button Grid.Row="1"
                HorizontalAlignment = "Center"
                VerticalAlignment = "Center"
                Padding="20 10"
                Margin="10"
                Content="SWAP"
                Click="ButtonBase_OnClick"/>
    </Grid>
</Window>

2. 分離コード:

C#
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        SwapControls();
    }

    private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
    {
        SwapControls();
    }

    private void SwapControls()
    {
        ContentControl.Content = ContentControl.Content?.GetType()
            == typeof(UserControl1)
            ? new UserControl2()
            : new UserControl1();
    }
}

コメント

タイトルとURLをコピーしました