Hello everyone,
The question may sound simple enough, and I've been doing research for the last two days, with no avail. I am a pure hobbyist, and unfortunately the only one interested in programming amongst friends and relatives, so I do not have exactly a proper background based on personal interaction. Thus I may lack some terms used amongst programmers - but I will learn happyly any bit I can.
Starting point:
I have a wpf desktop app (.Net 6.0). All I am trying at the moment is to set up a basic text editor. My XAML at the moment looks something like this:
>
So good so far. Now though I do use MVVM I leave things only concerning the view in codebehind (as you will see soon). Here is the code:
public partial class TextEditorView : UserControl
{
public TextEditorView()
{
InitializeComponent();
//cmbFontFamilies.ItemsSource = Fonts.SystemFontFamilies.OrderBy(f => f.Source);
//cmbFontSize.ItemsSource = new List() { 8, 9, 10, 11, 12, 14, 16, 18, 20, 22, 24, 26, 28, 36, 48, 72 };
rtbEditor.Focus();
}
private void ApplyPropertyValueToSelectedText(DependencyProperty formattingProperty, object value)
{
if (value == null)
return;
rtbEditor.Focus();
rtbEditor.Selection.ApplyPropertyValue(formattingProperty, value);
}
private void FontFamily_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
//try
//{
// FontFamily editValue = (FontFamily)e.AddedItems[0];
// ApplyPropertyValueToSelectedText(TextElement.FontFamilyProperty, editValue);
//}
//catch (Exception) { }
}
private void FontSize_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
//try
//{
// ApplyPropertyValueToSelectedText(TextElement.FontSizeProperty, e.AddedItems[0]);
//}
//catch (Exception) { }
}
As you can see, I commented most of the code out, because it is not related to my question. Only the constructor is in effect now.
What I want to achieve:
Coming back to my question header: All I want to do at the moment, is to start up my app, and have the caret inside the richtextbox, so that the user can write in it right away. Turns out everything I tried so far failed. Some code I tried:
- rtbEditor.Focus();
- rtbEditor.SelectAll();
- rtbEditor.CaretPosition = rtbEditor.CaretPosition.Document.ContentStart;
- rtbEditor.Selection.Select = rtbEditor.CaretPosition.Document.ContentStart;
...and a lot of combinations thereof.
This should be an easy task, but obviously I am missing something crucial here. Any suggestions?
thank you very much, and best regards
Barka
Amit MohantyPosted Dec 22, 2023, 12:00 PM
You can utilize the Loded event to ensure that the control is fully loaded before setting the focus.