Set focus on textbox in WPF
In XAML:
<StackPanel FocusManager.FocusedElement="{Binding ElementName=Box}">
<TextBox Name="Box" />
</StackPanel>
Set the focus on a textbox in xaml wpf
You can use the FocusManager.FocusedElement
attached property for this purpose. Here's a piece of code that set the focus to TxtB by default.
<StackPanel Orientation="Vertical" FocusManager.FocusedElement="{Binding ElementName=TxtB}">
<TextBox x:Name="TxtA" Text="A" />
<TextBox x:Name="TxtB" Text="B" />
</StackPanel>
You can also use TxtB.Focus()
in your code-behind if you don't want to do this in XAML.
Set focus on TextBox in WPF from view model
Let me answer to your question in three parts.
I'm wondering what is "cs.txtCompanyID" in your example? Is it a TextBox control? If yes, then you are on a wrong way. Generally speaking it's not a good idea to have any reference to UI in your ViewModel. You can ask "Why?" but this is another question to post on Stackoverflow :).
The best way to track down issues with Focus is... debugging .Net source code. No kidding. It saved me a lot of time many times. To enable .net source code debugging refer to Shawn Bruke's blog.
Finally, general approach that I use to set focus from ViewModel is Attached Properties. I wrote very simple attached property, which can be set on any UIElement. And it can be bound to ViewModel's property "IsFocused" for example. Here it is:
public static class FocusExtension
{
public static bool GetIsFocused(DependencyObject obj)
{
return (bool) obj.GetValue(IsFocusedProperty);
}
public static void SetIsFocused(DependencyObject obj, bool value)
{
obj.SetValue(IsFocusedProperty, value);
}
public static readonly DependencyProperty IsFocusedProperty =
DependencyProperty.RegisterAttached(
"IsFocused", typeof (bool), typeof (FocusExtension),
new UIPropertyMetadata(false, OnIsFocusedPropertyChanged));
private static void OnIsFocusedPropertyChanged(
DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
var uie = (UIElement) d;
if ((bool) e.NewValue)
{
uie.Focus(); // Don't care about false values.
}
}
}Now in your View (in XAML) you can bind this property to your ViewModel:
<TextBox local:FocusExtension.IsFocused="{Binding IsUserNameFocused}" />
Hope this helps :). If it doesn't refer to the answer #2.
Cheers.
How to set focus to the inner TextBox but with the blinking caret visible?
Your template is wrong. It should feel odd to you to put a TextBox
inside a TextBox
.
The TextBox
renders its content using a ScrollViewer
as host. This allows for text scrolling. The content host can be any FrameworkElement
in general. It must be named PART_ContentHost
.
Always check Microsoft Docs: Control Styles and Templates to get the default styles and templates, named parts and visual states of WPF controls. Here you also find the TextBox ControlTemplate Example and at the top a list of mandatory named elements that must be part of the template.
Fix your template by replacing the inner TextBox
with a ScrollViewer
named PART_ContentHost
:
<Style x:Key="SearchTextBox" TargetType="TextBox">
<Setter Property="BorderThickness" Value="0" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="TextBox">
<Border
BorderBrush="{StaticResource Grey200Brush}"
BorderThickness="1">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<glph:GlyphAwesome x:Name="SearchSymbol"
Grid.Column="0"
Glyph="search"
Margin="4"
FontFamily="{StaticResource MyFontFamily}"
Foreground="{StaticResource Grey200Brush}"
VerticalAlignment="Center"
HorizontalAlignment="Left"
FontSize="13"/>
<ScrollViewer x:Name="PART_ContentHost"
Grid.Column="1"
Margin="0" />
</Grid>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsKeyboardFocusWithin" Value="True">
<Setter TargetName="SearchSymbol"
Property="Visibilty"
Value="Collapsed" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Set focus on a textbox control in UserControl in wpf
Another option that you have is to create a bool IsFocused
property in your view model. Then you can add a DataTrigger
to set the focus when this property is true
:
In a Resources
section:
<Style x:Key="SelectedTextBoxStyle" TargetType="{x:Type TextBox}">
<Style.Triggers>
<DataTrigger Binding="{Binding IsFocused}" Value="True">
<Setter Property="FocusManager.FocusedElement"
Value="{Binding RelativeSource={RelativeSource Self}}" />
</DataTrigger>
</Style.Triggers>
</Style>
...
<TextBox Style="{StaticResource SelectedTextBoxStyle}" ... />
Note that at times, you may need to set it to false first to get it to focus (only when it is already true
):
IsFocused = false;
IsFocused = true;
wpf setting keyboard focus on textbox using xaml
According to @olitee's comment i used my gridview's IsVisible property to fire a DataTrigger and set the Focusmanager.FocusedElement to my Textbox.here is the code
<Style x:Key="trgFocus" TargetType="TextBox">
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=gvLoginPage, Path=IsVisible}" Value="true">
<Setter Property="FocusManager.FocusedElement" Value="{Binding ElementName=txtUserName}" />
</DataTrigger>
</Style.Triggers>
Now i am getting blinking cursor.Thanks @olitee and @Palak
Cannot set focus on TextBox in WPF
All this was caused by pressing tab button.
If it wasn't pressed, control stay focused as it should - and that was misleading.
When I pressed tab, then by default, the next control got focus, i.e. I handled the event, but it was passed further to containing control, which set focus on other control. Thus unexpected behaviour.
The solution was to set e.Handled
, instead of using Focus()
method (after which further processing of an event set focus to other control anyway), to true
in the event, so pressing tab event wasn't processed any further.
Example code:
private void txbUid_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key != Key.Tab) return; // here control doesn't loose focus
string stringUid = txbUid.Text;
long uid;
if (!TryParseUid(stringUid, out uid))
{
// no need to comment out anything
string errMsg = $"Niepoprawny kod UID: {stringUid}";
lblError.Text = errMsg;
this.LogError(errMsg);
txbUid.Text = "";
// mark event as handled
e.Handled = true;
return;
}
}
Set focus on TextBox in UserControl
Give this a try: FocusManager.SetFocusedElement
FocusManager.SetFocusedElement(parentElement, textBox)
or from the msdn website:
textBox.Focusable = true;
Keyboard.Focus(textBox);
Note: You can't set focus in a constructor. If you are, UI Elements have not been created at that point. You should set focus during the Loaded event of your control.
Related Topics
What's a Good Threadsafe Singleton Generic Template Pattern in C#
String.Replace() VS. Stringbuilder.Replace()
Best Way to Convert Callback-Based Async Method to Awaitable Task
Add Separator to String at Every N Characters
Using Lambda Expressions for Event Handlers
Winforms: Application.Exit VS Environment.Exit VS Form.Close
Wpf C#: Rearrange Items in Listbox via Drag and Drop
Hosting Clr in Delphi With/Without Jcl - Example
How to Format a Nullable Datetime with Tostring()
How to "Await Yield Return Dosomethingasync()"
Microsoft Office Excel Cannot Access the File 'C:\Inetpub\Wwwroot\Timesheet\App_Data\Template.Xlsx'
Why Can't I Have Protected Interface Members
Interfaces VS. Abstract Classes
Changing Project Port Number in Visual Studio 2013
Await Operator Can Only Be Used Within an Async Method
Loop Through All Controls of a Form, Even Those in Groupboxes