2015-02-25 4 views
-2

Я пишу Windows Phone 8.1 (WINRT) Приложение.Доступ к элементам данных в DataTemplate в Windows Phone 8.1

У меня есть listbox с datatemplate. Внутри datatemplate у меня есть сетка и текстовый блок. Как установить ширину сетки или текстового блока с C#?

Я пытался использовать методы DependencyObject VisualTreeHelper из Интернета, но не работал.

XAML:

<SemanticZoom x:Name="CategorySemanticZoom" 
              IsZoomOutButtonEnabled="True" 
              CanChangeViews="True" 
              Grid.Row="1"> 
           <SemanticZoom.ZoomedInView> 
            <ListView x:Name="Category_ListViewDetail" IsSwipeEnabled="True" IsTapEnabled="True" 
               IsItemClickEnabled="True" 
               IsZoomedInView="True" 
              ItemClick="Category_ListViewDetail_ItemClick" > 
             <ListView.ItemTemplate> 
              <DataTemplate> 
               <Grid x:Name="SubCategoryName_grid" 
                 x:FieldModifier="public" 
                 > 

                <TextBlock 
                 Text="{Binding SubCategoryName}" 
    x:Name="SubCategoryName_TextBlock" 
                 FontSize="26" 
                 Margin="30,0,10,0"           
                 TextTrimming="CharacterEllipsis"/> 
               </Grid> 
              </DataTemplate> 
             </ListView.ItemTemplate> 
             <ListView.GroupStyle> 
              <GroupStyle> 
               <GroupStyle.HeaderTemplate> 
                <DataTemplate> 
                 <Border Background="{StaticResource DefaultTheme_DarkBlueColor}" 
                   CornerRadius="6" 
                   HorizontalAlignment="Left" 
                   Margin="10,20,10,20" 
                   Tapped="Border_Tapped" 
                   VerticalAlignment="Center"> 
                  <TextBlock Text="{Binding CategoryName}" 
                    /> 
                 </Border> 
                </DataTemplate> 
               </GroupStyle.HeaderTemplate> 
               <GroupStyle.Panel> 
                <ItemsPanelTemplate> 
                 <VariableSizedWrapGrid Orientation="Vertical" 
                       Margin="0 0 0 0" 
                       ItemHeight="55"/> 
                </ItemsPanelTemplate> 
               </GroupStyle.Panel> 
              </GroupStyle> 
             </ListView.GroupStyle> 
             <ListView.ItemsPanel> 
              <ItemsPanelTemplate> 
               <StackPanel Orientation="Vertical" /> 
              </ItemsPanelTemplate> 
             </ListView.ItemsPanel> 
            </ListView> 
           </SemanticZoom.ZoomedInView> 
           <SemanticZoom.ZoomedOutView> 
            <ListView x:Name="Category_ListViewSummary" 
               Background="LightGray" 
               IsZoomedInView="False" 
               Opacity=".85"> 
             <ListView.ItemTemplate> 
              <DataTemplate> 
               <Border Background="{StaticResource DefaultTheme_DarkBlueColor}" 
                   CornerRadius="6" 
                   HorizontalAlignment="Left" 
                   Margin="10,10,10,10" > 

                <TextBlock Text="{Binding Group.CategoryName}" 
                    /> 
               </Border> 


              </DataTemplate> 
             </ListView.ItemTemplate> 
             <ListView.ItemsPanel> 
              <ItemsPanelTemplate> 
               <StackPanel Orientation="Vertical"/> 
              </ItemsPanelTemplate> 
             </ListView.ItemsPanel> 
            </ListView> 
           </SemanticZoom.ZoomedOutView> 
          </SemanticZoom> 

Как установить ширину SubCategoryName_grid или SubCategoryName_TextBlock из C#?

+0

Я знаю, что это не очень помогает, но зачем вам это делать в C#? почему бы не определить свойство для каждой модели, которая является вашим товаром (например, тот же класс, который имеет SubCategoryName, а затем реализовать IValueConverter? – zaitsman

+0

Я не использую MVVM/MVC :( –

+0

ну, у вас есть {Binding} там, верно? 're bound to something? – zaitsman

ответ

1
DependencyObject findElementInItemsControlItemAtIndex(ItemsControl itemsControl, 
                   int itemOfIndexToFind, 
                   string nameOfControlToFind) 
     { 
      if (itemOfIndexToFind >= itemsControl.Items.Count) return null; 

      DependencyObject depObj = null; 
      object o = itemsControl.Items[itemOfIndexToFind]; 
      if (o != null) 
      { 
       var item = itemsControl.ItemContainerGenerator.ContainerFromItem(o); 
       if (item != null) 
       { 
        depObj = getVisualTreeChild(item, nameOfControlToFind); 
        return depObj; 
       } 
      } 
      return null; 
     } 


     DependencyObject getVisualTreeChild(DependencyObject obj, String name) 
     { 
      DependencyObject dependencyObject = null; 
      int childrenCount = VisualTreeHelper.GetChildrenCount(obj); 
      for (int i = 0; i < childrenCount; i++) 
      { 
       var oChild = VisualTreeHelper.GetChild(obj, i); 
       var childElement = oChild as FrameworkElement; 
       if (childElement != null) 
       { 
        //Code to take care of Paragraph/Run 
        if (childElement is RichTextBlock || childElement is TextBlock) 
        { 
         dependencyObject = childElement.FindName(name) as DependencyObject; 
         if (dependencyObject != null) 
          return dependencyObject; 
        } 

        if (childElement.Name == name) 
        { 
         return childElement; 
        } 
       } 
       dependencyObject = getVisualTreeChild(oChild, name); 
       if (dependencyObject != null) 
        return dependencyObject; 
      } 
      return dependencyObject; 
     } 


     private void Category_ListViewDetail_Loaded(object sender, RoutedEventArgs e) 
     { 
      ListView ListViewObject = sender as ListView; 

      //For changing Detail Sub Categories Width: 

      int CategoriesCount = ListViewObject.Items.Count; 

      for (int i = 0; i < CategoriesCount; i++) 
      { 
       TextBlock SubCategory_TextBlockObject = findElementInItemsControlItemAtIndex(ListViewObject, i, "SubCategoryName_TextBlock") as TextBlock; 
       if (SubCategory_TextBlockObject != null) 
       { 
        SubCategory_TextBlockObject.Width = Window.Current.Bounds.Width - 50; 

       } 
      } 

      for (int i = 0; i < CategoriesCount; i++) 
      { 
       TextBlock Category_TextBlockObject = findElementInItemsControlItemAtIndex(ListViewObject, i, "CategoryName_InDetailView_Textblock") as TextBlock; 
       if (Category_TextBlockObject != null) 
       { 
        Category_TextBlockObject.Width = Window.Current.Bounds.Width - 30; 

       } 
      } 



     } 


     private void Category_ListViewSummary_Loaded(object sender, RoutedEventArgs e) 
     { 
      //For changing Summary Categories Width: 

      ListView ListViewObject = sender as ListView; 

      int CategoriesCount = GetCategoriesResultObject.MasterCategories[0].Categories.Count; 

      for(int i=0;i<CategoriesCount;i++) 
      { 
       TextBlock Category_TextBlockObject = findElementInItemsControlItemAtIndex(ListViewObject, i, "CategoryName_Textblock") as TextBlock; 
        if (Category_TextBlockObject != null) 
        { 
         Category_TextBlockObject.Width = Window.Current.Bounds.Width - 30; 
        } 
      } 

     } 
Смежные вопросы