如何:访问样式中没有名称的ControlTemplate生成的元素

时间:2014-09-25 20:52:15

标签: wpf

是否可以解决ControlTemplate在stlye中没有名称的生成元素?

以下是wpf组合框的默认控件模板的摘录:

<?xml version="1.0" encoding="utf-8"?>
<ControlTemplate TargetType="ComboBox" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:mwt="clr-namespace:Microsoft.Windows.Themes;assembly=PresentationFramework.Aero" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Grid Name="MainGrid" SnapsToDevicePixels="True">
    <Grid.ColumnDefinitions>
      <ColumnDefinition Width="*" />
      <ColumnDefinition Width="0" MinWidth="{DynamicResource {x:Static SystemParameters.VerticalScrollBarWidthKey}}" />
    </Grid.ColumnDefinitions>
    <Popup IsOpen="False" Placement="Bottom" PopupAnimation="{DynamicResource {x:Static SystemParameters.ComboBoxPopupAnimationKey}}" AllowsTransparency="True" Name="PART_Popup" Margin="1,1,1,1" Grid.ColumnSpan="2">
    </Popup>
    <ToggleButton IsChecked="False" BorderBrush="{TemplateBinding Border.BorderBrush}" Background="{TemplateBinding Panel.Background}" Grid.ColumnSpan="2">
    </ToggleButton>
    <ContentPresenter Content="{TemplateBinding ComboBox.SelectionBoxItem}" ContentTemplate="{TemplateBinding ComboBox.SelectionBoxItemTemplate}" ContentStringFormat="{TemplateBinding ComboBox.SelectionBoxItemStringFormat}" Margin="{TemplateBinding Control.Padding}" HorizontalAlignment="{TemplateBinding Control.HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding Control.VerticalContentAlignment}" SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}" IsHitTestVisible="False" />
  </Grid>
</ControlTemplate>

现在我想要做的是将ContentPresenter的IsHitTestVisible属性(在ControlTemplate中没有名称)更改为true,例如:

<ComboBox>
    <ComboBox.Resources>
        <Style TargetType="{x:Type ContentPresenter}"  >
            <Setter Property="IsHitTestVisible" Value="True" />
        </Style>
    </ComboBox.Resources>
</ComboBox>

不幸的是,这不起作用。它甚至可能吗?

如果没有,可以通过代码完成吗?

1 个答案:

答案 0 :(得分:1)

IsHitTestVisible是在本地设置的。所以要覆盖它,我们需要在本地设置它(只在代码隐藏中可行)。我们还可以通过使用更高优先级的来源(例如动画)来设置其值。您可以在此处定义定位ContentPresenter的样式。在该样式中,为Loaded事件定义EventTrigger,并将BooleanAnimationUsingKeyFramesDiscreteBooleanKeyFrame一起使用,如下所示:

<ComboBox>
  <ComboBox.Resources>
    <Style TargetType="{x:Type ContentPresenter}">
       <Style.Triggers>
           <EventTrigger RoutedEvent="Loaded">
             <BeginStoryboard>
               <Storyboard Storyboard.TargetProperty="IsHitTestVisible">
                  <BooleanAnimationUsingKeyFrames>
                     <DiscreteBooleanKeyFrame Value="True" KeyTime="0:0:0"/>
                  </BooleanAnimationUsingKeyFrames>      
               </Storyboard>
             </BeginStoryboard>
           </EventTrigger>
       </Style.Triggers>
    </Style>
  </ComboBox.Resources>
</ComboBox>

有关Dependency Property Value Precedence的更多信息。