一尘不染

在背后的代码中的DataTemplate中找到WPF元素

c#

我有一个数据模板

<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”元素?


阅读 221

收藏
2020-05-19

共1个答案

一尘不染

我在WPF程序中经常使用此功能来查找子元素:

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  */
  }
}
2020-05-19