访问用户控件中的主窗口控件

本文关键字:控件 窗口 用户 访问 | 更新日期: 2023-09-27 18:21:31

我的项目中有Window和三个UserControl,我有一个本身显示用户控件的控件

<Window x:Class="Hesabdar.winMain"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:pageTransitions="clr-namespace:WpfPageTransitions;assembly=WpfPageTransitions"
        Title="winMain" Height="500" Width="600" Loaded="Window_Loaded_1">
    <Grid>
        <pageTransitions:PageTransition Name="pageTransitionControl"  TransitionType="SlideAndFade" />
    </Grid>
</Window>

UserControl我有Button

<UserControl x:Class="Hesabdar.ucMain"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" Height="500" Width="600">
    <Grid>
          <Button Content="Manege" HorizontalAlignment="Left" Margin="391,163,0,0" Click="Button_Click_1"/>
    </Grid>
</UserControl>

如何控制pageTransitionControlUserControl导航到pageTransitionControl到其他userControl

编辑:

主窗口的代码隐藏:

ucMain objUC = new ucMain(); //Declare Instance Of user Control 
pageTransitionControl.ShowPage(objUC); // Show Instance of usercontrol in PageTransitionControl

只是我想通过单击UserControl中的按钮在主窗口中运行方法ShowPage pageTransitionControl

访问用户控件中的主窗口控件

您可以从 UserControls 代码后面找到如下所示的 PageTransition 控件:

public static PageTransition FindPageControl(DependencyObject child)
{
    DependencyObject parent= VisualTreeHelper.GetParent(child);
    if (parent == null) return null;
    PageTransition page = parent as PageTransition;
    if (page != null)
    {
        return page;
    }
    else
    {
        return FindPageControl(parent);
    }
}

然后你可以像这样使用它:

this.FindPageControl(this).ShowPage(...);

你真正需要的是使用 MVVM 模式。请改用内容控件。并将用户控件引用传递给其 Content 属性。你可以从中得到想法,比如:

yourContentControl.Content = new UserControl1();