使用ControlTemplate维护默认的可视属性

时间:2009-08-26 21:50:57

标签: .net wpf xaml controltemplate

为了将触发动画应用到我应用中的所有ToolTip,我使用的是ControlTemplate。但是,当使用ControlTemplate时,ToolTip会失去所定义的所有默认视觉属性,我相信主题。除了那些覆盖的属性外,我如何保留所有属性?

使用以下代码

<ToolTip Opacity="0.8">
  <ToolTip.Content>
    <StackPanel>
      <Label FontWeight="Bold" Background="DarkSlateBlue" Foreground="White">
        WpfApplication1
      </Label>
      <Label>
        Click to create another button
      </Label>
    </StackPanel>
  </ToolTip.Content>
</ToolTip>

我得到了我想要的结果:

alt text http://img29.imageshack.us/img29/1488/controltemplateno.png

但是当我调整代码以使用ControlTemplate时:

<ControlTemplate x:Key="controltemplateToolTip" TargetType="{x:Type ToolTip}">
  <ContentPresenter Content="{TemplateBinding Content}" />  
  <ControlTemplate.Triggers>
    <EventTrigger RoutedEvent="ToolTip.Loaded">
      <BeginStoryboard>
        <Storyboard TargetProperty="Opacity">
          <DoubleAnimation From="0" To="0.8" Duration="0:0:0.2" />
        </Storyboard>
      </BeginStoryboard>
    </EventTrigger>
  </ControlTemplate.Triggers>
</ControlTemplate>
<Style TargetType="{x:Type ToolTip}">
  <Setter Property="Template" Value="{StaticResource controltemplateToolTip}" />
</Style>
...
<ToolTip>
  <ToolTip.Content>
    <StackPanel>
      <Label FontWeight="Bold" Background="DarkSlateBlue" Foreground="White">
        WpfApplication1
      </Label>
      <Label>
        Click to create another button
      </Label>
    </StackPanel>
  </ToolTip.Content>
</ToolTip>

我得到以下内容:

alt text http://img43.imageshack.us/img43/8217/controltemplateyes.png

如您所见,主题默认边框,背景等未得到维护。我不想明确地设置它们,因为我希望它们根据用户的主题进行调整。我该如何解决这个问题?我是以错误的方式解决这个问题吗?

1 个答案:

答案 0 :(得分:2)

您无法从主题样式继承ControlTemplate。但你没必要。使用DataTemplates实现您的目标。这是一个简单的例子:

<Page
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Page.Resources>
  <Style TargetType="{x:Type ToolTip}">
  <Style.Triggers>
    <EventTrigger RoutedEvent="ToolTip.Loaded">
      <BeginStoryboard>
        <Storyboard TargetProperty="Opacity">
          <DoubleAnimation From="0" To="0.8" Duration="0:0:0.5" />
        </Storyboard>
      </BeginStoryboard>
    </EventTrigger>
  </Style.Triggers>
  </Style>

<DataTemplate x:Key="ToolTipContentTemplate">
<StackPanel>
      <Label FontWeight="Bold" Background="DarkSlateBlue" Foreground="White">
        WpfApplication1
      </Label>
      <Label>
        Click to create another button
      </Label>
    </StackPanel>
</DataTemplate>
  </Page.Resources>

  <Grid>  
<Button Content="Hello">
<Button.ToolTip>
<ToolTip ContentTemplate="{StaticResource ToolTipContentTemplate}">
  <ToolTip.Content>
    Doesn't matter in this case
  </ToolTip.Content>
</ToolTip>
</Button.ToolTip>
</Button>
  </Grid>
</Page>

您可以将其粘贴到Kaxaml,然后对其进行测试。

希望这有帮助。