2

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

编辑:

我尝试过这样的事情,但它不起作用。

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

这没用。正确的方法是什么?

4

2 回答 2

4

您可以拥有一个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");
        }
    }
于 2012-08-21T11:58:22.213 回答
0

我认为这并没有什么问题,如果您对控件在窗口的生命周期内保留在内存中感到满意的话。另外,Amadeus Hein 的回答。

于 2012-08-21T12:03:49.923 回答