2013-02-13 78 views
0

當我將作爲資源對象的應用程序條附加到頁面時,我無法顯示應用程序欄。無法以編程方式加載應用程序條

下面的代碼未能產生一個工作appbar:

的App.xaml

<AppBar x:Key="RegisterHome_TopAppBar" > 
     <AppBar.Content> 
      <Grid> 
       <StackPanel Orientation="Horizontal" HorizontalAlignment="Center"> 
        <Button x:Name="RegisterHome_MaterialsButton" /> 
        <Button x:Name="RegisterHome_ServicesButton" /> 
       </StackPanel> 
      </Grid> 
     </AppBar.Content> 
    </AppBar> 

一些代碼隱藏文件

 var view = flipView.SelectedItem as Register.Home; 

     AppBar appbar = Application.Current.Resources["RegisterHome_TopAppBar"] as AppBar; 

     view.TopAppBar = appbar; 

注: 當我使用此代碼,它工作正常:

  var appbar = new AppBar(); 
      StackPanel sp = new StackPanel(); 
      sp.Orientation = Orientation.Horizontal; 
      Button myButton = new Button(); 
      myButton.Content = "Click Me"; 
      sp.Children.Add(myButton); 
      appbar.Content = sp; 

      view.TopAppBar = appbar; 

回答

1

將UI元素聲明爲資源通常是個壞主意。當你這樣做時,你每次訪問它並在不同地點使用它時都沒有獲得新實例。你會得到一個單一的實例,在這種情況下,整個應用程序。 UI元素不能擁有多個父母,但是如果您在兩個地方使用該資源,或者甚至在同一控件的兩個實例中使用了該資源,則違反了該要求。

相反,您應該使用模板作爲資源,這將生成相同用戶界面的新副本,並在使用模板的任何地方注入它們。在這種情況下,您可以將Content標記中的所有內容都轉換爲DataTemplate,然後獲取該資源並將其分配給新的AppBar實例的ContentTemplate屬性。這樣你每次都得到一個單獨的實例,但是同樣的子對象和佈局。

相關問題