1

我使用 WP7 项目。我已经定义了许多 ContentTemplates 的样式按钮。这些 ContentTeplates 包括形状(为简单起见,我们使用矩形):

<Button x:Name="button1" 
        Style="{StaticResource ButtonStyle1}" 
        ContentTemplate="{StaticResource DataTemplate1}">
</Button>

<Button x:Name="button2" 
        Style="{StaticResource ButtonStyle1}" 
        ContentTemplate="{StaticResource DataTemplate2}">
</Button>
...

<DataTemplate x:Key="DataTemplate1">
    <Rectangle Height="100" Width="100" Fill="{QUESTION_HERE}"/>
</DataTemplate>

我希望 Rectangle 的 Fill 属性为

  1. 等于托管按钮的前景色
  2. 按下或禁用按钮时相应更改

我怎样才能做到这一点?


我不太好的解决方案

在 WinRT,我使用 RelativeSource 方法,效果很好:

Fill="{Binding Foreground, RelativeSource={RelativeSource TemplatedParent}}" 

不幸的是,在 WP 无法正常工作。原因是 WP 的 ContentPresenter 没有 ForegroundProperty,而在 WinRT 有。

所以我尝试在 ContentPresenter 定义我自己的附加 DP 并在 Button 模板中使用它:

Button.Template >> ContentControl.Template >>

<ContentPresenter 
    local:FrameworkElementExtensions.Foreground="{TemplateBinding Foreground}"

你知道当我在 ContentPresenter 中定义 DP 时,RelativeSource 绑定开始工作。

但不好的一面是当 Button 被按下时,Rectangle 的 Fill 会延迟几毫秒更新。 这看起来不太好,我寻求更好的解决方案

4

1 回答 1

0

这将适用于 SL5 或 WPF

如果您使用 .Button而不是ContentPresenter.

Fill="{Binding Foreground, RelativeSource={RelativeSource FindAncestor, AncestorType=Button}}"

您还可以定义AncestorType=ButtonBase是否需要相同的模板来处理其他类型的按钮,例如RepeatButtonToggleButton

编辑:

这是 SL3/4 或 WP7 的 hack

将 aTextBlock放入您的DataTemplate并绑定到其前景。

<DataTemplate>
    <Grid>
        <TextBlock x:Name="ForegroundProvider" Width="0" Height="0" Opacity="0"/>
        <Path Fill="{Binding Foreground, ElementName=ForegroundProvider}" ..../>
    </Grid>
</DataTemplate>

这很丑陋,但那是 WP7 ...... :(

于 2013-01-10T10:37:17.430 回答