在 wpf 中显示用户控件的替代方法

2024-01-10

我想知道是否有其他显示方式usercontrols inside mainwindow在WPF应用程序中。 目前我利用的可见性属性usercontrols单击按钮一次显示一个用户控件。我将用户控件的可见性设置为Hidden单击按钮后,我会更改可见性。它工作完美。但这是正确的方法吗?

EDIT:

我尝试过类似的方法,但它不起作用。

mainwindow.xaml:

<Window x:Class="WpfApplication4.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication4"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="54*" />
        <RowDefinition Height="257*" />
    </Grid.RowDefinitions>
    <Grid Grid.Row="1">
        <ContentControl Content="{Binding CurrentView}"/>
    </Grid>
    <Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="25,12,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
    <Button Content="Button" Height="23" HorizontalAlignment="Right" Margin="0,12,251,0" Name="button2" VerticalAlignment="Top" Width="75" />
</Grid>

</Window>

有两个用户控件,即 UserControl1 和 UserControl2。后面的代码中:

 private UserControl currentview;


    private UserControl CurrentView
    {
        get
        {
            return this.currentview;
        }
        set
        {
            this.currentview = value;
            //RaisePropertyChanged("CurrentView");
        }
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        UserControl1 uc1 = new UserControl1();
        CurrentView = uc1;
    }

这是行不通的。正确的做法是什么?


你可以有一个ContentControl(在 MainWindow xaml 中),并将其内容绑定到视图,以便您可以在代码中切换它。像这样:

<Window x:Class="WpfApplication4.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication4"
    DataContext="{Binding RelativeSource={RelativeSource Self}}"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="54*" />
        <RowDefinition Height="257*" />
    </Grid.RowDefinitions>

    <ContentControl Grid.Row="0" Content="{Binding CurrentView}"/>

    <Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="25,12,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
    <Button Content="Button" Height="23" HorizontalAlignment="Right" Margin="0,12,251,0" Name="button2" VerticalAlignment="Top" Width="75" />
</Grid>

</Window>

后面的代码中:

    private UserControl currentView;

    public UserControl CurrentView
    {
        get
        {
            return this.currentView;
        }

        set
        {
            if (this.currentView == value)
            {
                return;
            }

            this.currentView = value;
            RaisePropertyChanged("CurrentView");
        }
    }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 wpf 中显示用户控件的替代方法 的相关文章

随机推荐