简体   繁体   English

如何在C#中获取WPF UserControl的父页面?

[英]How to get WPF UserControl's Parent Page in C#?

I have a uCtrl of type UserControl in a parentPg of type Page (instead of a Window ). 我在类型Page (而不是Window )的uCtrl具有UserControl类型的parentPg And I want to access that parentPg in uCtrl class so that I can bind some uCtrl 's property to parentPg 's Control . 我想在uCtrl类中访问该parentPg ,以便可以将某些uCtrl的属性绑定到parentPgControl

Like as we get in case of Window . 就像我们遇到Window

public partial class uCtrl : UserControl
{
    Window parentWin;

    public uCtrl()
    {
        parentWin = Window.GetWindow(this);
    }

    public bool IsPrptReady
    {
        get
        {
            //accesing parent Window's control

            if (((pWin)(parentWin)).txt.Text != "")
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }   
}

In above code snippet, I am getting parent Window (ie of type pWin ) in uCtrl of type UserControl and then sets its Property (ie IsPrptReady ) based on parents Window's Control ie txt of type 'TextBox'. 在上面的代码片段,我得到父Window (即类型的pWin中) uCtrl类型的UserControl ,然后设置其Property (即IsPrptReady基于父母窗口的) Control ,即txt类型“文本框”的。

I want to do the same thing, but in case of Page not Window . 我想做同样的事情,但是在Page不是Window情况下。 I have seen a lot of questions like this but nothing solves my problem. 我已经看到了很多的问题,像这样 ,但没有解决我的问题。 Any help will be appreciated. 任何帮助将不胜感激。

The XAML code is as below. XAML代码如下。

<Page x:Class="Stego.Pages.EnDeCoding"
      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" 
      xmlns:local="clr-namespace:Test"
      xmlns:userControls="clr-namespace:Test.UserControls"
      mc:Ignorable="d" 
      d:DesignHeight="600" d:DesignWidth="800"
      >
      <Grid>
           <userControls:uCtrl x:Name="uCtrlName"/>
      </Grid>
</Page>

The second answer in the question you linked to provides the answer you need; 您链接到的问题的第二个答案提供了您需要的答案; specifically the use of the VisualTreeHelper. 专门使用VisualTreeHelper。

Alternatively, you could add a [dependency] property to the user control of type Page and bind the property to the page instance the control is hosted within. 或者,您可以向[Page]类型的用户控件添加[dependency]属性,并将该属性绑定到该控件所在的页面实例。 Something like: 就像是:

<Page x:Name="page">
  <local:UCtrl Page="{Binding ElementName=page}"/>
</Page>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM