Tokfrans
Tokfrans

Reputation: 1959

Set font size of individual character in WPF TextBox

I'm trying to make an animation where I catch the TextChanged event and make the newly added character to fade from being fontsize 0 to the set size by me.

I have the animation working, but, when I type in a new character the whole contents of the textbox changes with it, but I only want the pressed key.

This is the code I have:

private void CreateTextboxAnimation(TextBox box)
    {
        // Info Needed By Control
        double FontSize = box.FontSize;
        //
        DoubleAnimation Anim = new DoubleAnimation();
        Anim.From = 0.0;
        Anim.To = FontSize;
        Anim.Duration = new Duration(TimeSpan.FromMilliseconds(100));
        Anim.AutoReverse = false;
        SB = new Storyboard();
        SB.Children.Add(Anim);
        Storyboard.SetTargetName(Anim, box.Name);
        Storyboard.SetTargetProperty(Anim, new PropertyPath(TextBox.FontSizeProperty));

    }
    private Storyboard SB;

    private void TestBox_TextChanged(object sender, TextChangedEventArgs e)
    {
        if (TestBox.IsLoaded == true)
        {
            SB.Begin(TestBox);
        }
    }

Upvotes: 1

Views: 1107

Answers (1)

Sheridan
Sheridan

Reputation: 69985

You cannot have that level of control over the text using standard text controls in WPF. You will need to delve into the deep world of Glyphs and GlyphRuns. Using this lowest level of functionality, you can have complete control over each character displayed. From the linked page:

A glyph is a physical representation of a character in a given font. Characters might have many glyphs, with each font on a system potentially defining a different glyph for that character.

A glyph run represents a contiguous set of glyphs that all have the same font face and size, as well as the same client drawing effect, if any.

Here is a good page on MSDN introducing Glyphs and GlyphRuns which shows some code examples:

Introduction to the GlyphRun Object and Glyphs Element


UPDATE >>>

The other method that you could have used to increase the size of just part of the text would be to manipulate Run elements within the TextBox, but I don't think that it would work for text input. Check out the WPF How to arrange TextBlock with different Fontsize at bottomline post here on StackOverflow for an example of that (just for text output).

Finally, I've just thought that you could do what you want if you create a collection of chars and display them in a ListBox with a custom animated StackPanel with Orientation="Horizontal" set as the ListBox.ItemsPanel. You could simply animate each item as it is added. Here are a number of useful articles on how to create custom animated panels, starting simply and getting more complex:

How to create a Custom Layout Panel in WPF
Creating a sliding panel in WPF
Animated WPF Panels

Upvotes: 2

Related Questions