1

我正在嘗試爲我的WP應用創建自定義基頁。我通過創建從PhoneApplicationPage繼承這樣的新cs類文件,這樣做:將控制權添加到自定義基頁

public class BasePage: PhoneApplicationPage 
{ 
    //handle common non-visual stuff here 
} 

的問題是,我想使用BasePage每個頁面上添加一個控制,但BasePage的沒有LayoutRoot或任何視覺元素,我可以附加控制。有沒有辦法將相同的控件添加到使用BasePage的所有頁面,以便我不必每次都複製/粘貼它?

編輯:根據TriggerPin的答案添加XAML。我創建了一個新的XAML文件我BasePage.cs但這是BasePage.g.cs引發錯誤: 「MyApp.MainPage已經包含了‘_contentLoaded’的定義」(即「LayoutRoot」和「的InitializeComponent」及類似消息)

<local:BasePage 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone" 
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    xmlns:local="clr-namespace:MyApp.Template" 
    x:Class="MyApp.MainPage" 
    mc:Ignorable="d"> 
+0

this.Children.Add – ebattulga 2013-02-15 17:52:03

+0

@ebattulga - 我試過了,但是'Children'沒有出現在Intellisense中。 (編譯結果「不包含兒童定義...」) – XSL 2013-02-15 17:53:55

+0

創建網格或容器控件並設置爲this.Content = yourGrid; – ebattulga 2013-02-15 19:19:55

回答

2

注意,在默認情況下,從派生的PhoneApplicationPage類型是部分

public partial class MainPage : PhoneApplicationPage 

局部定義,您可以拆分到多個文件類定義。這種類型最常見的定義是在.cs和.xaml文件之間進行分割。

<phone:PhoneApplicationPage x:Class="MyProject.MainPage" 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"> 

    <!-- Custom layout here --> 

</phone:PhoneApplicationPage> 

如果你讓你實現一個局部類,並提供基礎XAML代碼,你就可以做你想要達到的目標。

+0

感謝您的幫助。我用我嘗試創建的新XAML文件更新了我的問題,但它引發了一個錯誤。 (我已經向BasePage.cs文件中添加了「partial」) – XSL 2013-02-15 19:04:40

+0

您還需要發佈錯誤 – 2013-02-17 08:05:55

+0

「MyApp.MainPage已經包含'_contentLoaded'的定義」就是其中之一。其他類似,但'_contentLoaded'被其他方法和屬性取代。 – XSL 2013-02-17 17:36:45

0

您需要一個容器,它必須是面板類型,至少用於添加您的子控件。一個Page只是一個UserControl,它不能直接將你的UIElement添加到它中。

試試這個:

Panel container = // init it from your page, you must have a root element in page. 
container.Children.Add(new TextBlock()); // your children control. 

我這樣做是在Win8中。