Peter Wone
Peter Wone

Reputation: 18825

How to accept focus C# WPF UserControl

I'm trying to create a date edit UserControl, but using TextBlock rather than TextBox because I want a single input context rather than manage six possible foci.

How do I accept focus? I tried setting Focusable to TRUE but it appears not to be enough. What else do I have to do?

Upvotes: 6

Views: 5244

Answers (1)

sa_ddam213
sa_ddam213

Reputation: 43634

Sounds like you need to set KeyboardFocus to the element

Example:

<UserControl x:Class="MyControl"
       xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
       xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
       mc:Ignorable="d" 
       d:DesignHeight="300" d:DesignWidth="300"
       FocusManager.IsFocusScope="True"
       FocusManager.FocusedElement="{Binding ElementName=mytextBlock}">
    <Grid>
       <TextBox Name="mytextBlock" />
    </Grid>
</UserControl>

Or in codeBehind:

FocusManager.SetFocusedElement(this, mytextblock);
Keyboard.Focus(mytextblock);

Upvotes: 7

Related Questions