Wednesday, 23 February 2011

Silverlight C1RichTextBox Selection Problem

During developing with C1RichTextBox, I found a problem that I have to pay attention, the problem is like this:
  1. Include the namespaces in the XAML codes:
       1:  <navigation:Page ...
       2:   xmlns:c1rtbtb="clr-namespace:C1.Silverlight.RichTextBox;assembly=C1.Silverlight.RichTextBox.Toolbar" 
       3:   xmlns:c1rtb="clr-namespace:C1.Silverlight.RichTextBox;assembly=C1.Silverlight.RichTextBox"
       4:   xmlns:c1="clr-namespace:C1.Silverlight;assembly=C1.Silverlight">

  2. Add a C1RichTextBoxToolBar, a C1RichTextBox and a TextBlock to the Grid
       1:  <c1rtbtb:C1RichTextBoxToolbar 
       2:      RichTextBox="{Binding ElementName=rtb}" 
       3:      Grid.Row="0" />
       4:  <StackPanel Grid.Row="1" Grid.Column="0">
       5:      <c1rtb:C1RichTextBox 
       6:      x:Name="rtb"             
       7:      Margin="5" MinHeight="50"
       8:      SelectionChanged="rtb_SelectionChanged"/>
       9:      <TextBlock x:Name="textBlockMessage" MinWidth="250" Margin="5"/>
      10:  </StackPanel>

  3. Write C# codes for SelectionChanged event which is rtb_SelectionChanged:
  4.    1:  private void rtb_SelectionChanged(object sender, EventArgs e)
       2:  {
       3:      textBlockMessage.Text = (this.rtb.Selection.Start.Element as C1Run).Text;
       4:  }
  5. Run the Application, and watch the text change in textBlockMessage(is a TextBlock)
Now, let's input some text like this, see the screenshot:









    Now the C1TextElement 1234567890ABCDEF9999 has three different C1Runs, they are
    C1Run: 1234567890
    C1Run: ABCDEF
    C1Run: 9999

    if you put the cursor in between any of the two C1Runs, for example, if we put the cursor between 0 and A, like this:










    you can see that the textBlockMessage.Text is outputting 1234657890 which is the previous C1TextElement of the cursor, very good, now if we put the cursor between F and 9, like this:










    what you can see that the this.rtb.Selection.Start.Element is still pointing to the previous element of the cursor. very good, but if you keeping changing the position of the cursor by using the keyboard and mouse, sometimes, you will find the output like this:









    well, this time, the this.rtb.Selection.Start.Element is pointing to the element behind the cursor.

    for the user, this is ok, but for developers who want to use the Selection.Start as the condition, this is a big problem. So please remember : If the start or the end is in between two different C1Runs,the start and end property of the C1RichTextBox.Selection is unpredictable. So if you are developing on C1RichTextBox.Selection and find your codes actioning weirdly, please check this issue

    No comments:

    Post a Comment