在代码后台中查找DataTemplate中的WPF元素

20

我有一个data-template。

<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>

我在表单上有一个按钮。我需要在数据模板中更改矩形的比例(scaleTransform)。我该如何在上述按钮的Button_Click事件中访问'rectangleBarChart'元素?

2个回答

38

我在我的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  */
  }
}

谢谢,我已经成功进入if块并找到元素,但是在更改矩形的某些属性(例如rectangle.Fill=Brushes.Red)后,这些更改没有反映回来。(我正在使用上述DataTemplate作为ListBox的ItemTemplate)。那么如何将更改更新到ListBox中呢? - Robert Langdon
你真是个圣人!这个方法太棒了。我之前试过其他的解决方案都不行。 - nikotromus

4

不要这样做。如果你需要更改中的某些内容,则绑定相应的属性并修改底层数据。我建议将绑定到数据/视图模型上的(请参见MVVM),而不是使用事件,这样你就已经在正确的上下文中了,视图不需要做任何事情。


@H. B. - 我正在使用以下DataTemplate:<ListBox Name="barChartListBox" ItemsSource="{Binding}" BorderThickness="0" ItemTemplate="{DynamicResource BarChartItemsTemplate}" ItemsPanel="{DynamicResource BarChartItemsPanel}" Margin="36,-3,48,12"></ListBox>我能够在我的代码后台中访问ListBox,但我想要缩放矩形并将更改再次反映到UI中。为此,我执行了以下操作: rectangle.Fill = Brushes.MediumVioletRed; rectangle.Height = 10; rectangle.LayoutTransform = new ScaleTransform(2, 1); - Robert Langdon
@GrowWithWPF:所以呢?没有什么阻止你在模板中绑定所有这些属性,并改变绑定的对象。 - H.B.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接