本文介绍了在代码隐藏中的 DataTemplate 中查找 WPF 元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据模板

<Window.Resources>
         <DataTemplate x:Key="BarChartItemsTemplate">
         <Border Width="385" Height="50">
            <Grid>
               <Rectangle Name="rectangleBarChart" Fill="MediumOrchid" StrokeThickness="2" Height="40" Width="{Binding}" HorizontalAlignment="Right" VerticalAlignment="Bottom">
                  <Rectangle.LayoutTransform>
                     <ScaleTransform ScaleX="4"/>
                  </Rectangle.LayoutTransform>
               </Rectangle>
               <TextBlock Margin="14" FontWeight="Bold" HorizontalAlignment="Right" VerticalAlignment="Center" Text="{Binding}">
                  <TextBlock.LayoutTransform>
                     <TransformGroup>
                        <RotateTransform Angle="90"/>
                        <ScaleTransform ScaleX="-1" ScaleY="1"/>
                     </TransformGroup>
                  </TextBlock.LayoutTransform>
               </TextBlock>
            </Grid>
         </Border>
      </DataTemplate>
  </Window.Resources>

我在表单上有一个按钮.我需要更改 dataTemplate 中的矩形的 scale(scaleTransform).我应该如何访问上述按钮的 Button_Click 事件中的 'rectangleBarChart' 元素?

I have a button on the form. I need to change the scale(scaleTransform) the rectangle from the dataTemplate. How am I supposed to access the 'rectangleBarChart' element in the Button_Click event of the above mentioned button ?

推荐答案

我在我的 WPF 程序中经常使用这个函数来查找子元素:

I use this function a lot in my WPF programs to find children elements:

public IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
   if (depObj != null)
   {
       for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
       {
           DependencyObject child = VisualTreeHelper.GetChild(depObj, i);

           if (child != null && child is T)
               yield return (T)child;

           foreach (T childOfChild in FindVisualChildren<T>(child))
               yield return childOfChild;
       }
   }
}

用法:

foreach (var rectangle in FindVisualChildren<Rectangle>(this))
{
  if (rectangle.Name == "rectangleBarChart")
  {
    /*   Your code here  */
  }
}

这篇关于在代码隐藏中的 DataTemplate 中查找 WPF 元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 21:08