My main window has a content control that I load a user control into. I can’t seen to set the focus to a text box in the user control. I’ve tried several suggested methods like textBox1.Focus() and Keyboard.Focus() and FocusManager.SetFocusedElement() but they don’t seem to work.
I’m not tied to this way of loading the user control if there is a better way. It seems like I’m missing something pretty fundamental regarding either focus or the ContentControl so I thought I’d ask the experts instead of continuing to shot gun the problem.
Any ideas?
MainWindow.xaml:
<Grid>
<ContentControl Name="NavFrame"/>
</Grid>
MainWindow.xaml.cs:
protected override void OnInitialized(EventArgs e)
{
this.NavFrame.Content = new UserControl1();
base.OnInitialized(e);
}
UserControl1.xaml:
<Grid>
<TextBox Height="23" HorizontalAlignment="Left" Margin="93,79,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" />
</Grid>
UserControl1.xaml.cs:
protected override void OnInitialized(EventArgs e)
{
textBox1.Focus();
// FocusManager.SetFocusedElement(this, textBox1);
// Keyboard.Focus(textBox1);
base.OnInitialized(e);
}
If you put the
textBox1.Focus()into the loaded event for the user control rather thanOnInitializedit seems to work correctly.Something as simple as this works as well, if you want to give focus on times other than OnLoad…
UserControl1.xaml.cs:
MainWindow.xaml.cs: