2014-03-01 22 views
0

因此,在我的頁面中我添加了一個Pivot。我命名爲Pivot MainPivot。在MainPivot裏面我編輯了Title Template。在TitleTemplate內部,我添加了2個TextBlocks。一個被稱爲AppTitle和另一個名爲UserText無法使用VisualTreeHelper訪問控件

我想要做的是設置兩個AppTitleUserText的使用C#文本。爲此,我設法從this link獲得VisualTreeHelper。雖然它的「如何訪問列表框」我添加了一些變化,看看它是否工作。

所以我的代碼。 XAML的編輯MainPivot

<DataTemplate x:Key="MainPivotEditedTemplate"> 
<StackPanel x:Name="Stak" Orientation="Vertical" Width="0"> 
    <TextBlock x:Name="AppTitle" HorizontalAlignment="Left" TextWrapping="NoWrap" Width="443" Margin="0,0,-443,0" FontSize="22"/> 
    <TextBlock x:Name="UserText" HorizontalAlignment="Left" TextWrapping="NoWrap" Width="443" Margin="0,0,-443,0" FontFamily="Segoe WP SemiLight" FontSize="23"/> 
</StackPanel> 
</DataTemplate> 

這裏是爲VisualTreeHelper代碼:

private T FindFirstElementInVisualTree<T>(DependencyObject parentElement) where T : DependencyObject 
{ 
    var count = VisualTreeHelper.GetChildrenCount(parentElement);  

    if (count == 0) 
      return null; 

     for (int i = 0; i < count; i++) 
     { 
      var child = VisualTreeHelper.GetChild(parentElement, i); 

      if (child != null && child is T) 
      { 
       return (T)child; 
      } 
      else 
      { 
       var result = FindFirstElementInVisualTree<T>(child); 
       if (result != null) 
        return result; 
      } 
     } 
     return null;  
} 

這裏有一個的意思改變TextBlock中的文本代碼:

public MainMenu() 
{ 
    InitializeComponent(); 

    Pivot apptitle = this.MainPivot.ItemContainerGenerator.ContainerFromIndex(0) as Pivot; 
    Pivot usertext = this.MainPivot.ItemContainerGenerator.ContainerFromIndex(1) as Pivot; 

    TextBlock _apptitle = FindFirstElementInVisualTree<TextBlock>(apptitle); 
    TextBlock _usertext = FindFirstElementInVisualTree<TextBlock>(usertext);  

    _apptitle.Text = "APPLICATION TITLE"; 
    _usertext.Text = "USER TEXT";  
} 

現在我的問題是當我調試應用程序,它給了我一個錯誤說: Reference is not a valid visual DependencyObject.

,並顯示該線路VisualTreeHelper方法: var count = VisualTreeHelper.GetChildrenCount(parentElement);

任何人都可以幫我嗎?我想要做的就是訪問這兩個文本塊並更改文本。謝謝!

回答

1

爲什麼把它當成模板呢?

爲什麼不直接設置標題

<phone:Pivot.Title> 
    <StackPanel Name="Stak" Orientation="Vertical" Width="0"> 
     <TextBlock Name="AppTitle" HorizontalAlignment="Left" TextWrapping="NoWrap" Width="443" Margin="0,0,-443,0" FontSize="22"/> 
     <TextBlock Name="UserText" HorizontalAlignment="Left" TextWrapping="NoWrap" Width="443" Margin="0,0,-443,0" FontFamily="Segoe WP SemiLight" FontSize="23"/> 
    </StackPanel> 
</phone:Pivot.Title> 

和訪問的TextBlocks直接在後面的代碼

AppTitle.Text = "APPLICATION TITLE"; 
UserText.Text = "USER TEXT"; 
+0

這是有益的,我向你表示感謝:)。原因是我一直想知道如何訪問控制,例如文本塊等內部模板,即樞紐模板。你知道我如何從數據模板中訪問控件嗎? –

+0

@ Ahmed.C那麼,如果你必須這樣做,最好按名稱搜索項目。只搜索TextBlock是有風險的。你的代碼是錯誤的,因爲你使用了ContainerFromIndex,並且在一點上發送null給FindFirstElementInVisualTree。爲什麼不按名稱在MainPivot.Title內搜索,並找到它們,然後編輯它們?網上有很多例子,如何按名稱搜索。儘管如此,在這種特殊情況下,我認爲沒有理由這樣做。 –