代码之家  ›  专栏  ›  技术社区  ›  Mark

Silverlight/WPF中的TemplateBinding和ContentPresenter

  •  1
  • Mark  · 技术社区  · 14 年前

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

    我的ItemTemplate是一个非常简单的数据模板:

    <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>
    

    一切正常。

    但我想做的是,当一个项目被选中时(即选中的视觉状态),我希望数据模板中的文本块将其前景颜色更改为黑色而不是白色,并使字体大小更大。但我似乎找不到一个干净的方法来完成这项工作,因为模板绑定似乎无法从数据模板中获得。

    有什么想法吗?

    2 回复  |  直到 14 年前
        1
  •  2
  •   John Bowen    14 年前

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

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

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

        2
  •  0
  •   TrueHarlequin    13 年前

    不要认为这个答案在当前的Silverlight版本中已经起作用了,ContentPresenter上的附件甚至不再构建。还有人知道吗?