[英]Access to main window control in UserControl
我的項目中有Window
和三個UserControl
,我有一個控件,可以顯示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>
這怎么可能控制pageTransitionControl
從UserControl
導航pageTransitionControl
到其他userControl
編輯:
MainWindow背后的代碼:
ucMain objUC = new ucMain(); //Declare Instance Of user Control
pageTransitionControl.ShowPage(objUC); // Show Instance of usercontrol in PageTransitionControl
我想通過點擊UserControl
的按鈕在mainWindow中運行pageTransitionControl
方法ShowPage
。
您可以從后面的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模式。 請改用ContentControl。 並將usercontrol引用傳遞給其Content屬性。 你可以從中得到想法,比如:
yourContentControl.Content = new UserControl1();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.