Monday, March 12, 2007

Text length measurement? It's really easy with WPF

Don't you remember how it was to measure the length of your text in pixels? Do you really remember methods named GetLineFromCharIndex, Bounds and MeasureText?

Let's do it in WPF:

TextBox myText = new TextBox();
Rect textRext = myText.GetRectFromCharacterIndex(myText.Text.Length);

That's all, folks. Now you have the boundaries of your text in pixels. You can even measure the size of text up to your cursor position by using CaretIndex property of TextBox. Don't it really easy?

 

<Window x:Class="TextMeasurement.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:m="clr-namespace:TextMeasurement"
        Name="myWindow" 
    Title="TextMeasurement" Height="300" Width="300"
    >
  <StackPanel>
    <StackPanel Orientation="Horizontal">
      <TextBlock>The text length is:  </TextBlock>
      <TextBlock Name="mySize" Text="{Binding ElementName=myWindow, Path=TextSize}"/>
    </StackPanel>
    <TextBox Name="myText" TextChanged="onChanged"/>
  </StackPanel>
</Window>

 


public partial class Window1 : System.Windows.Window

{

    public static readonly DependencyPropertyKey TextSizePropertyKey = DependencyProperty.RegisterReadOnly("TextSize",

        typeof(double), typeof(Window1),

        new UIPropertyMetadata((double)0));

    public static DependencyProperty TextSizeProperty = TextSizePropertyKey.DependencyProperty;

    public double TextSize

    {

        get { return (double)GetValue(TextSizeProperty); }

    }

 

 

    public Window1()

    {

        InitializeComponent();

 

    }

 

    void onChanged(object sender, TextChangedEventArgs e)

    {

        Rect textRext = myText.GetRectFromCharacterIndex(myText.Text.Length);

 

        SetValue(TextSizePropertyKey, textRext.Right);

    }

 

}

 

Have a nice day with WPF :)

No comments: