2014-09-25 23 views
0

是否可以解決ControlTemplate生成的元素中沒有名稱的問題?如何訪問在樣式中​​沒有名稱的ControlTemplate生成的元素

下面是一個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屬性(它沒有在一個名字例如:

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

不幸的是,這是行不通的。它甚至有可能嗎?

如果不是,可以通過代碼來完成嗎?

回答

1

那麼IsHitTestVisible是在本地設置的。因此,要覆蓋這一點,我們需要在本地進行設置(只能在代碼隱藏中執行)。我們還可以通過使用更高優先級的來源(如動畫)來設置其值。在這裏您可以定義一個定位爲ContentPresenter的樣式。在這種風格定義一個EventTrigger爲Loaded事件並使用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

相關問題