编辑:
发布整个代码以使答案更清楚。而且我也没有任何例外。
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:h="clr-namespace:WpfApplication4"
Title="MainWindow"
Width="525"
Height="350">
<Grid>
<h:UC1 x:Name="Uc1" />
<h:UC2 x:Name="Uc2" Visibility="Hidden" />
</Grid>
</Window>
MainWindow.xaml.cs:
using System.Windows;
namespace WpfApplication4
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
}
UC1.xaml:
<UserControl x:Class="WpfApplication4.UC1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
d:DesignHeight="300"
d:DesignWidth="300"
mc:Ignorable="d">
<Grid>
<Ellipse Width="100"
Height="100"
Margin="65,113,0,0"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Fill="CornflowerBlue"
Stroke="Black" />
<Button Width="75"
Margin="177,239,0,0"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Click="ButtonBase_OnClick"
Content="ABCD" />
</Grid>
</UserControl>
UC1.xaml.cs:
using System.Windows;
using System.Windows.Controls;
namespace WpfApplication4
{
/// <summary>
/// Interaction logic for UC_.xaml
/// </summary>
public partial class UC1 : UserControl
{
public UC1()
{
InitializeComponent();
}
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
Window parentWindow = Application.Current.MainWindow;
if (parentWindow.GetType() == typeof(MainWindow))
{
(parentWindow as MainWindow).Uc1.Visibility = Visibility.Collapsed;
(parentWindow as MainWindow).Uc2.Visibility = Visibility.Visible;
}
}
}
}
UC2.xaml:
<UserControl x:Class="WpfApplication4.UC2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
d:DesignHeight="300"
d:DesignWidth="300"
mc:Ignorable="d">
<Grid>
<Ellipse Width="100"
Height="100"
Margin="169,22,0,0"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Fill="Orange"
Stroke="Black" />
</Grid>
</UserControl>
UC2.xaml.cs:
using System.Windows.Controls;
namespace WpfApplication4
{
/// <summary>
/// Interaction logic for UC2.xaml
/// </summary>
public partial class UC2 : UserControl
{
public UC2()
{
InitializeComponent();
}
}
}