Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 298
Peter Wone Avatar asked Jan 14 '13 00:01

Peter Wone


1 Answers

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);
like image 87
sa_ddam213 Avatar answered Sep 30 '22 01:09

sa_ddam213