如何以编程方式更改ItemContainerStyle中的边框背景颜色?

时间:2013-08-25 11:46:38

标签: wpf templates styles findname

我有一个TreeView,它有自己的Style,它有自己的ItemContainerStyle。在ItemContainerStyle中,我有一个名为“SelectedRectangle”的边框。现在我想通过使用此代码(我在Internet上找到它)来更改此“SelectedRectangle”的背景颜色:

    Border brd = (Border)lstDbTree.Template.FindName("SelectedRectangle", lstDbTree); //dosnt work - returns 'null'
    brd.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#7B7A7C")); // Null Pointer Exception

我不知道如何访问ItemContainerStyle XAML以编程方式操作它。

守则:

Shell.xaml

    <TreeView DockPanel.Dock="Bottom" Name="lstDbTree"
      ...
      ItemContainerStyle="{StaticResource DbTreeItemStyle}"
      ...
    />

CoreStyles.xaml

    <Style TargetType="TreeViewItem" x:Key="DbTreeItemStyle">
      <Setters...>
      <Setter Property="Template">
        <Setter.Value>
          <ControlTemplate TargetType="TreeViewItem">
            ...
              <Border x:Name="SelectedRectangle" BorderBrush="#44ffffff" BorderThickness="1" Grid.Column="1" CornerRadius="1" IsHitTestVisible="False" Opacity="0" Background="#555355"/>
            ...
          </ControlTemplate>
        </Setter.Value>
      </Style

Shell.xaml.cs

    private void ColorB_OnClick(object sender, RoutedEventArgs e)
    {
        Border brd = (Border)lstDbTree.Template.FindName("SelectedRectangle", lstDbTree); //dosnt work
        brd.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#7B7A7C"));
    }

我想做什么

enter image description here

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

我可以使用ItemContainerGenerator修复此问题:

    private void ColorB_OnClick(object sender, RoutedEventArgs e)
    {
        //TODO: Do this for all Items and not only for the "Selected Item"
        TreeViewItem tvi = lstDbTree.ItemContainerGenerator.ContainerFromItem(lstDbTree.SelectedItem) as TreeViewItem;
        Border brd = (Border)tvi.Template.FindName("SelectedRectangle", tvi);
        brd.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#7B7A7C"));
    }