質問

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>

これを行うにはどうすればよいですか

役に立ちましたか?

解決

あなたが正しく理解していれば、おそらく次のようなことができ、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>

他のヒント

FontSizeで ValueConverter を使用できる場合がありますプロパティ..しかし、それらがControlTemplate内で動作するかどうかは100%確信していません。

コードビハインドでFontSizeを設定する場合は、ControlTemplateからFontSizeを削除してから、コードビハインドでListBoxItemに設定する必要があります。すべてのListBoxItemに同じサイズを設定する場合は、コードビハインドでListBoxのFontSizeを設定するだけです。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top