2014-03-13 56 views
0

我想從另一個C#類獲得一個帶有自己名字的XAML元素,但它總是返回null,爲什麼?FindName返回null

這裏的目標XAML與它的C#類:

XAML: 
<Page 
    x:Class="myApp.SubSpace.SomePage" 
    IsTabStop="false" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:local="using:myApp.SubSpace" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    mc:Ignorable="d"> 

    <Grid x:Name="target"> 
    </Grid> 
</Page> 

C#: 
using Windows.Foundation; 
using Windows.UI.Xaml; 
using Windows.UI.Xaml.Controls; 

namespace myApp.SubSpace 
{ 
    public sealed partial class SomePage : Page 
    { 
     public SomePage() 
     { 
      InitializeComponent(); 
     } 
    } 
} 

下面是它給了我一個空的結果代碼:

using myApp.SubSpace; 
using Windows.Foundation; 
using Windows.UI.Xaml; 
using Windows.UI.Xaml.Controls; 

namespace myApp.Core 
{ 
    public class Main 
    { 
     private Grid target; 
     public Main() { 
      FrameworkElement page = new SomePage(); 
      this.target = (Grid)page.FindName("target"); 
     } 
    } 
} 

的代碼是非常簡單的,但是非常重要的事那裏。在調用一個新的Main對象後,其target字段爲空。怎麼了?

在此先感謝!

+0

你想要什麼? –

+0

@HighCore正如我所說的,代碼非常簡單,但之後必須編輯'target'對象。 – JordiVilaplana

+0

[FindName返回null]的可能重複(http://stackoverflow.com/questions/2214737/findname-returning-null) – nvoigt

回答

0
Grid myGrid= 
this.FindName("target") as Grid; 
0

我意識到這是不是在OP的代碼的情況下,但我有同樣的錯誤(從FindChild返回null),對我來說這是一個調用FindChild在頁面的構造函數調用InitializeComponent()之前調用的問題。確保在查看孩子之前,一切都已初始化並準備就緒。