在ControlTemplate的触发器中,如何访问ControlTemplate主体中定义的元素?

时间:2011-04-19 09:12:29

标签: wpf xaml triggers controltemplate setter

我有以下(简化)ControlTemplate:

<ControlTemplate x:Key="ImageButtonTemplate" TargetType="{x:Type controls:ImageButton}">
    <Grid x:Name="Grid">
      <Border [StuffRemoved]/>
      <StackPanel [StuffRemoved]>
        <Image [StuffRemoved] />
        <ContentPresenter [StuffRemoved] />
      </StackPanel>      

        <Grid.RenderTransform>
            <ScaleTransform x:Name="ImgBtnScale"/>
        </Grid.RenderTransform>
    </Grid>

    <ControlTemplate.Triggers>

        <!-- problem here! -->
        <Trigger Property="IsPressed" Value="True">
            <Trigger.Setters>
                <Setter  TargetName="ImgBtnScale" Property="ScaleX" Value="0.9"/>
                <Setter TargetName="ImgBtnScale" Property="ScaleY" Value="0.9"/>
            </Trigger.Setters>
        </Trigger>      


        <!-- rest of the stuff works okay-->

        <Trigger Property="IsMouseOver" Value="True">
            <Trigger.EnterActions>
                <BeginStoryboard>
                    <Storyboard>
                        <DoubleAnimation Storyboard.TargetName="ImgBtnScale" Storyboard.TargetProperty="ScaleX"
                            To="1.2" Duration="0:0:0.1"/>
                        <DoubleAnimation Storyboard.TargetName="ImgBtnScale" Storyboard.TargetProperty="ScaleY"
                            To="1.2" Duration="0:0:0.1"/>
                    </Storyboard>
                </BeginStoryboard>
            </Trigger.EnterActions>

            <Trigger.ExitActions>
                <BeginStoryboard>
                    <Storyboard>
                        <DoubleAnimation Storyboard.TargetName="ImgBtnScale" Storyboard.TargetProperty="ScaleX"
                            To="1" Duration="0:0:0.1"/>
                        <DoubleAnimation Storyboard.TargetName="ImgBtnScale" Storyboard.TargetProperty="ScaleY"
                            To="1" Duration="0:0:0.1"/>
                    </Storyboard>
                </BeginStoryboard>
            </Trigger.ExitActions>      
        </Trigger>

    </ControlTemplate.Triggers>
  </ControlTemplate>

它没有编译,说:

Cannot find the target 'ImgBtnScale'. (The target must appear before any Setters, Triggers or Conditions that use it.)

那么如何访问ImgBtnScale

2 个答案:

答案 0 :(得分:1)

您无法通过名称访问它,因为ScaleTransform不是可视树中的元素,它只是元素属性的值(Grid)。

您可以做的是通过定义它的父元素访问转换的属性。例如:

<DoubleAnimation Storyboard.TargetName="Grid" Storyboard.TargetProperty="RenderTransform.(ScaleTransform.ScaleX)" .../>

答案 1 :(得分:1)

我认为,问题在于ScaleTransform不是Visual元素。所以它不能在VisualTree中找到。您应该尝试在网格上设置触发器并更改整个ScaleTransform。