19

私がしたいのは、ボタンをクリックするだけで wpf ウィンドウの内容を変更/スライドすることです。私はwpfが初めてで、これを行う方法がわかりません。誰かが私を助けることができれば、私はとても感謝しています。ビデオチュートリアルが最適です。

4

1 に答える 1

41

ウィンドウのコンテンツを UserControl に入れることができます。ウィンドウには、コンテンツ コントロールとコンテンツを変更するためのボタンしかありません。ボタンをクリックすると、コンテンツ コントロールのコンテンツ プロパティを再割り当てできます。

このための小さな例を作成しました。

MainWindow の XAML コードは次のようになります。

<Window x:Class="WpfApplication3.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Button Content="Switch" Click="ButtonClick"/>
        <ContentControl x:Name="contentControl" Grid.Row="1"/>
    </Grid>
</Window>

ソリューションに 2 つの UserControls を追加しました。MainWindow の CodeBehind は次のようになります。

    public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        this.contentControl.Content = new UserControl1();
    }

    private void ButtonClick(object sender, RoutedEventArgs e)
    {
        this.contentControl.Content = new UserControl2();
    }
}

更新 MyUserControl という小さなユーザー コントロールを作成しました。xaml マークアップは次のようになります

<UserControl x:Class="WpfApplication.MyUserControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <StackPanel Orientation="Vertical">
        <Label Content="This is a label on my UserControl"/>
        <StackPanel Orientation="Horizontal" HorizontalAlignment="Left">
            <Button Content="Testbutton 1" Margin="5"/>
            <Button Content="Testbutton 2" Margin="5"/>
        </StackPanel>
        <CheckBox Content="Check Me"/>
    </StackPanel>
</UserControl>

上記のボタン クリック イベントでは、このユーザー コントロールの新しいインスタンスをコンテンツ コントロールに割り当てることができます。これは次の方法で実行できます。

this.contentControl.Content = new MyUserControl();
于 2013-05-31T10:47:57.083 に答える