如何切换WPF UserControl?

时间:2014-09-11 08:02:42

标签: c# wpf xaml

当UserControl1中的按钮被附加到MainWindow时,我想更改为UserControl2。

MainWindow.xaml

<Viewbox Grid.Row="1" HorizontalAlignment="Center">
        <Grid>
            <local:A x:Name="a" Margin="0,0" Width="1200" /> <--UserControl1
            <local:B x:Name="b" Margin="0,0" Width="1200" /> <--UserControl2
        </Grid>
    </Viewbox>

MainWindow.xaml.cs

public MainWindow()
    {
        this.Closed += this.WindowClosed;
        this.InitializeComponent();

        this.a.Visibility = Visibility.Visible;
        this.b.Visibility = Visibility.Hidden;
    }

如果点击按钮而不是

this.a.Visibility = Visibility.Hidden; 
this.b.Visibility = Visibility.Visible;

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

将以下代码放入按钮点击事件

Window w = Window.GetWindow(this);
if(null != w)
{
    ((UserControl)w.FindName("a")).Visibility = Visibility.Hidden;
    ((UserControl)w.FindName("b")).Visibility = Visibility.Visible;
}