【问题标题】:How can I change the font size of a label in my ControlTemplate如何更改 ControlTemplate 中标签的字体大小
【发布时间】:2009-01-19 21:47:03
【问题描述】:

在我的 WPF ListBox 中,我有一个带有 ControlTemplate 的 ListBoxItem 样式。在那个 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>

我该怎么做?

【问题讨论】:

    标签: wpf controltemplate templatebinding


    【解决方案1】:

    如果我对您的理解正确,您可能可以执行以下类似操作,只需更改 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>
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          猜你喜欢
          • 2011-09-25
          • 1970-01-01
          • 1970-01-01
          • 2020-05-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-10-27
          • 2019-09-11
          相关资源
          最近更新 更多