I have a UserControl
that is placed into a Page. How do I access the Page
the UserControl
is in?
My user case, I want the constructor or method of my UserControl
to add to the hierarchy of the Page it's located on. When the button of the UserControl
is clicked, it will place or make visible a Canvas
on top of it's Parent
Page
In a simple case of UserControl
added to a Page
, the First Parent
of the UserControl
when it is placed in a page is the FrameworkElement
and the Parent
of the FrameworkElement
will be the page.
For Example: If MyUserControl
is my UserControl
and MainPage
is the page that I am adding the UserControl
to, Then you can get the MainPage
from inside the UserControl
where Button
is clicked on is like below.
var page = ((FrameworkElement)myControl.Parent).Parent;
and then you can check for page type and process your commands accordingly.
Here is a full snippet
private void Button_Tapped(object sender, TappedRoutedEventArgs e)
{
var page = ((FrameworkElement)myControl.Parent).Parent;
if (page.GetType() == typeof(MainPage))
{
(page as MainPage).ShowData();
}
}
Good Luck.
UserControl的定义中包含Page,因此您应该能够从this.Page
进行访问。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.