Letterspacing (tracking) with TextBlock in WPF?

3.1k views Asked by At

What is the best way to do letterspacing (tracking) with TextBlock in WPF?

I would think TextBlock.Typography would have taken care of this but it doesn't. What is the best approach?

2

There are 2 answers

0
Lars Tabro Sørensen On

I used the approach suggested by Kreol, and found this to be working except that some letters are wider than others.

When using a UniformGrid every column have same width by definition. This lead to variable spacing between letters.

Instead I used a stackpanel with horizontal orientation, and a left margin on each element:

<Grid>
    <ItemsControl ItemsSource="{Binding SomeString}" HorizontalAlignment="Center" VerticalAlignment="Center">
            <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                            <StackPanel Orientation="Horizontal" />
                        </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
                <ItemsControl.ItemContainerStyle>
                        <Style>
                            <Setter Property="Control.Margin" Value="1,0,0,0"/>
                            <Setter Property="Control.Foreground" Value="#1E395B"/>
                         </Style>
                </ItemsControl.ItemContainerStyle>
        </ItemsControl>
</Grid>
0
Kreol On

It seems that this problem cannot be solved easily. You can google and find something like this http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/789c3e1b-e3ae-476f-b37f-d93ef6d0cb7b/ (approach with glyphs). But taking into account the fact that String is enumerable collection sometimes you can solve your problem with markup like this:

<Grid>
    <ItemsControl>
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <UniformGrid Rows="1"/>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.ItemsSource>
            <System:String>
                Hello World
            </System:String>
        </ItemsControl.ItemsSource>
    </ItemsControl>         
</Grid>

Tuning this markup (panels, templates) you can get any desired layout of string. And of course you could separate this markup to a special UserControl. Just as a variant for particular cases.