【问题标题】:TemplateBinding and ContentPresenter in Silverlight/WPFSilverlight/WPF 中的 TemplateBinding 和 ContentPresenter
【发布时间】:2011-05-13 14:14:23
【问题描述】:

我有一个列表框,其中包含为 ItemContainer 和 ItemTemplate 样式定义的模板。

我的 ItemTemplate 是一个非常简单的 DataTemplate:

<DataTemplate x:Key="DataTemplate1">
    <Grid x:Name="grid">
    <TextBlock TextWrapping="Wrap" Text="{Binding}" Foreground="White" FontSize="24" />    
    </Grid>
</DataTemplate>

而且ItemContainer也很简单:

<Grid x:Name="Grid" HorizontalAlignment="Stretch" Height="Auto" SnapsToDevicePixels="true" Width="373" Background="{x:Null}">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="37"/>
    </Grid.ColumnDefinitions>
    <VisualStateManager.VisualStateGroups>
        <VisualStateGroup x:Name="SelectionStates">
            <VisualState x:Name="Unselected"/>
            <VisualState x:Name="Selected"/>
            <VisualState x:Name="SelectedUnfocused"/>
        </VisualStateGroup>
    </VisualStateManager.VisualStateGroups>
    <ContentPresenter x:Name="contentPresenter" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" RenderTransformOrigin="0.5,0.5" HorizontalAlignment="Stretch" Margin="2,0,0,0" d:LayoutOverrides="Width">
    </ContentPresenter>
    <Image x:Name="image" HorizontalAlignment="Center" Margin="0,0,0,1" Source="/MyApp;component/Images/icon_arrowcircle.png" Stretch="Uniform" Width="37" Grid.Column="1" VerticalAlignment="Center" Opacity="0"/>
</Grid>

一切正常。

但我想要做的是,当一个项目被选中(即 Selected 视觉状态)时,我希望 DataTemplate 中的 TextBlock 将其前景颜色更改为黑色而不是白色,并使字体大小更大。但我似乎无法找到一种干净的方法来执行此操作,因为 DataTemplate 似乎没有提供 TemplateBinding。

有什么想法吗?

【问题讨论】:

    标签: wpf silverlight binding


    【解决方案1】:

    如果您希望 ItemContainer 的模板控制 Foreground,您可以将其设置在那里而不是 ItemTemplate 中。 TextBlock.Foreground 和 TextBlock.FontSize 可以用作附加属性,并将继承自父值:

    <ContentPresenter TextBlock.Foreground="White" TextBlock.FontSize="18"/>
    

    需要从 ItemTemplate 中删除这些属性的设置,以避免覆盖继承的值。然后,您可以从 VisualState 动画中设置所需的任何值。

    【讨论】:

    • 行得通!非常感谢 John,但作为对此的扩展,我怎样才能触发这些值在不同视觉状态下的变化?
    • 其实你可以 :) 我刚刚发现了 Charles charlespetzold.com/blog/2007/09/080231.html的这个博客
    【解决方案2】:

    不要认为答案在当前 Silverlight 版本中不再有效,ContentPresenter 上的附加或 poerties 甚至不再构建。其他人能解决这个问题吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-11
      相关资源
      最近更新 更多