我正在创建一个UserControl并在MainWindow中调用它
我将可见性用作隐藏以不显示UserControl窗口,因此我在MainWindow上创建一个按钮并单击以将可见性更改为可见
在UserControl代码中,我创建了另一个按钮,调用MainWindow Visibility并再次将其设置为Hidden
这是正确的工作方式吗?
我的代码:
UserControl.xaml
<Grid Background="White">
<TextBlock Height="125" TextWrapping="Wrap" Text="My UserControl" VerticalAlignment="Center" FontSize="48" HorizontalAlignment="Center" Width="345"/>
<Button Content="HidenUserControl" HorizontalAlignment="Center" Height="75" VerticalAlignment="Bottom" Width="255" Click="HidenUserControl"/>
</Grid>
UserControl.xaml.cs
public partial class MyUserControl : UserControl
{
public MyUserControl()
{
InitializeComponent();
}
private void HidenUserControl(object sender, RoutedEventArgs e)
{
MainWindow main = (MainWindow)Window.GetWindow(this);
main.EnableUserControl.Visibility = Visibility.Hidden;
}
}
MainWindow.xaml
<Grid>
<Border Name="EnableUserControl" Background="#66000000" Visibility="Hidden">
<local:MyUserControl Margin="105,105,72,155" />
</Border>
<Button Content="ShowUserControl" HorizontalAlignment="Left" Margin="680,25,0,0" VerticalAlignment="Top" Width="75" Click="ShowUseControl"/>
</Grid>
MainWindow.xaml.cs
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void ShowUseControl(object sender, RoutedEventArgs e)
{
EnableUserControl.Visibility = Visibility.Visible;
}
}
您可以简单地写:
private void HidenUserControl(object sender, RoutedEventArgs e)
{
Visibility = Visibility.Hidden;
}
无需引用MainWindow