Reputation: 1572
I am working with a textbox/richtextbox component in WPF and I need to import additional textboxes into it. Currently, I use a RichTextbox control that inserts additional custom textboxes into (they are necessary since it is an expression that cannot otherwise be done). The problem I'm having is I need to focus into the the textbox when the cursor is adjacent to the textbox inside of the richtexbox. It seems to ignore the component and skip over it. Does anyone else have a solution to this?
I can't seem to get any control to the cursor or components inside of the RichTexbox in WPF.
Upvotes: 2
Views: 838
Reputation: 1572
The UIComponent that is embedded inside my RichTextBox is actually a digit which contains 3 TextBoxes (base, superscript, and subscript). The problem I had was that the cursor couldn't focus into the digit component.
The function I was looking for is this . . .
RichTextBox.CaretPosition.GetAdjacentElement(LogicalDirection Direction)
here is my code . . .
public class MathRichTextbox : RichTextBox
{
public MathRichTextbox()
{
this.PreviewKeyDown += MathRichTextbox_PreviewKeyDown;
}
void MathRichTextbox_PreviewKeyDown(object sender, KeyEventArgs e)
{
Digit expr = null;
switch (e.Key)
{
case Key.Left:
expr = findAdjacentMathDigits(LogicalDirection.Backward);
break;
case Key.Right:
expr = findAdjacentMathDigits(LogicalDirection.Forward);
break;
}
if (expr != null)
this.Dispatcher.BeginInvoke(
new ThreadStart(() => expr.FocusBase()),
System.Windows.Threading.DispatcherPriority.Input, null);
}
private Digit findAdjacentMathDigits(LogicalDirection direction)
{
Digit expr = null;
if (Selection.Text.Length == 0)
{
DependencyObject dpObj = CaretPosition.GetAdjacentElement(
direction);
// is it contained in BlockUIContainer?
expr = CaretPosition.GetAdjacentElement(
direction) as Digit;
// is it onctained in a InlineUIContainer?
if (expr == null)
{
InlineUIContainer uiWrapper =
CaretPosition.GetAdjacentElement(
direction) as InlineUIContainer;
if (uiWrapper != null)
expr = uiWrapper.Child as Digit;
}
}
return expr;
}
}
Upvotes: 2
Reputation: 2133
As I said in the comment, you should try to use a Run instead.
A Run
is not much different from a TextBox. Let me give you an example:
You want to add this string "This is an example" at the beginning of a Paragraph
in a RichTextBox:
Paragraph _para //I assume you have this
TextPointer pointer=_para.ContentStart;
Run run=new Run("This is an example",pointer);
That's it. You can set FontSize, FontFamily and ... other properties like a TextBox
.
run.Foregroung=Brushes.Red;
Hope it helps.
Upvotes: 1