在wpf窗口中动态更改内容

时间:2013-05-31 10:37:40

标签: wpf

我想要做的是点击按钮更改/滑动wpf窗口的内容。我是wpf的新手,并不知道如何做到这一点。如果有人能帮助我,我将非常感激。任何视频教程都是最好的。

1 个答案:

答案 0 :(得分:35)

您可以将窗口内容放入UserControl中。您的窗口只有一个内容控件和一个更改内容的按钮。单击该按钮,您可以重新分配内容控件的content-property。

我为此做了一个小例子。

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>

我在解决方案中添加了两个UserControl。 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-markup看起来像

<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>

在上面的按钮单击事件中,您可以将此usercontrol的新实例分配给内容控件。你可以这样做:

this.contentControl.Content = new MyUserControl();