2

在我的 WPF ListBox 中,我有一个 ListBoxItem 的 ControlTemplate 样式。在那个 ControlTemplate 里面我定义了一个标签。根据一些细节,我需要更改标签的字体大小。所以从我的代码隐藏中,我需要确定字体应该是什么,然后我需要设置它。

这是我使用 ControlTemplate 的风格(我已经去掉了一些不相关的控件)

<Style x:Key="RecordTabList" TargetType="{x:Type ListBoxItem}">
            <Setter Property="Background" Value="{DynamicResource RecordIndexTabBackcolor}" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate>        
                            <Label
                                x:Name="myLabel" Grid.Column="0" Grid.ColumnSpan="1" Grid.Row="0" Grid.RowSpan="1" Margin="3,-2,0,-2" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Foreground="{DynamicResource RecordIndexTabForeground}" 
                                FontSize="10" Height="Auto" BorderThickness="3,0,0,0"
                                Content="{Binding Path=Name}" />
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>

我怎样才能做到这一点?

4

3 回答 3

5

如果我理解正确,您可能可以执行类似于以下的操作,只需更改 ListBoxItem 本身的 FontSize 属性;它将自动反映在您的标签上。将其复制到 VS 中并查看它的实际效果!

<Window.Resources>
    <Style TargetType="ListBoxItem">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="ListBoxItem">
                    <Label Content="{TemplateBinding Content}" FontSize="{TemplateBinding FontSize}"/>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>
<Grid>
    <ListBox Margin="12">
        <ListBoxItem Content="Test 1" FontSize="14"/>
        <ListBoxItem Content="Test 2" FontSize="18"/>
        <ListBoxItem Content="Test 3" FontSize="22"/>
    </ListBox>
</Grid>
于 2009-01-22T06:27:54.123 回答
0

您可能可以在 FontSize 属性上使用ValueConverter .. 但我不能 100% 确定它们是否在 ControlTemplate 中工作。我似乎记得 Silverlight 有问题,但我不记得它是否在WPF。

于 2009-01-19T22:21:13.780 回答
0

如果要在后面的代码中设置 FontSize,则应从 ControlTemplate 中删除 FontSize,然后在代码隐藏中为 ListBoxItem 设置它。如果要为所有 ListBoxItems 设置相同的大小,只需在代码隐藏中设置 ListBox 的 FontSize。

于 2009-02-03T04:17:20.467 回答