2012-07-13 58 views
0

我有一個WrapPanel定義爲XAML如下...在WPF我怎麼訪問WrapPanel從代碼隱藏

<Page x:Class="SelectImages" 
     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" 
     d:DesignHeight="320" d:DesignWidth="480" 
     Title="Select Images"> 
    <Grid> 
     <WrapPanel Name="MyImagePanel" Width="Auto" Height="Auto" Margin="10,50,10,10" ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollBarVisibility="Auto" Orientation="Horizontal"> 

     </WrapPanel> 

    </Grid> 
</Page> 

當我嘗試使用WrapPanel如下面我的代碼背後,我得到一個運行時錯誤「未將對象引用設置爲對象的實例」。

Private Sub AddImageToPanel(Image As FileSystemInfo) 
    MyImagePanel.Children.Add(NewPicture(Image)) 
End Sub 

有誰能告訴我我做錯了什麼嗎?

+1

'MyImagePanel'將在'InitializeComponent()'被調用之前爲'null'。如果'Image'爲'null'或不是'FileSystemInfo','Image As FileSystemInfo'可能爲'null'。找出究竟是什麼'null'。或者發佈異常堆棧。 – Clemens 2012-07-13 11:53:30

+0

查看調用堆棧以查看null異常。 – 2012-07-13 12:17:16

+0

'MyImagePanel'爲空。我還測試了同一頁面上的其他控件。它們都返回相同的錯誤,即使它們是在XAML中聲明的,所有控件在運行時都是空的。 – Hades 2012-07-13 12:17:29

回答

0

我被導航到使用此頁......

Dim SelectImagesPage As New SelectImages(FolderPath, SelectedProductID) Me.NavigationService.Navigate(SelectImagesPage)

似乎在構造函數不會自動初始化的組件。將InitializeComponent()添加到我的頁面上的構造函數,現在它都可以工作。