在wpf窗口中动态更改内容

Saa*_*han 14 wpf

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

Tom*_*tom 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>
Run Code Online (Sandbox Code Playgroud)

我已经为解决方案添加了两个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();
    }
}
Run Code Online (Sandbox Code Playgroud)

更新 我创建了一个名为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>
Run Code Online (Sandbox Code Playgroud)

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

this.contentControl.Content = new MyUserControl();
Run Code Online (Sandbox Code Playgroud)

  • 但用户控件也是预先构建的.如何在运行时创建用户控件? (2认同)