focus does not enter targeted user control properly - wpf

I've got a user control, consisting of a text box and two buttons.
the control is placed on a dialog box and when i tab over the dialog
controls, I experience proper behavior - first the text box is focused,
then one button, then the other.
However, when I set the user control as a target of a keyboard shortcut
set with "_" for a label (say press alt+r for "_Row count") the user control
does not receive any focus. Tried implementing "gotkeyboardfocus" and setting
the focus to the textbox control there but it doesn't work.

A UserControl isn't focusable by default so you have to turn it on in order to get this to work.
<my:UserControl1 x:Name="userControl11" Focusable="True" .../>
<Label Target="userControl11">_Row count</Label>
And then you can focus the desired TextBox inside of the UserControl when it recieves Focus
private void UserControl_GotFocus(object sender, RoutedEventArgs e)
{
textBox.Focus();
}

Hi I recently encountered focus problem. What I did is create a method called SetFocus() from inside my user control. Then inside that usercontrol I set the focus directly to my textbox control after calling .SetFocus() from consumer.
public void SetFocus()
{
this.txtCommand.Focus();
}

Related

How to use the context menu of the parent in a textbox

I have a listbox with several controls. Each control contains an custom autocompletebox which contains a System.Windows.Controls.AutoCompleteBox. When I right click on the control a custom contextm menu shows up. But with a right click on the textbox there appears the default contextmenu of the TextBox (with Copy, Cut and Paste).
My goal is to show my custom context menu with a right click on the TextBox.
Further informations:
My custom context menu is defined in the DataTemplate of the ListBox but I could define it in the Ressources or somewhere else as well.
I tried:
- when I null the context menu of the custom autocompletebox or the System.Windows.Controls.AutoCompleteBox of it, there is no effect at all
Thanks for every help ;)
You can either bind the context menu property to parent element's context menu or bind to the context menu once you define in the resource.xaml
Try using PreviewMouseDown instead of MouseDown to handle the MouseDown event.
In XAML:
<ListBox Margin="3" PreviewMouseDown="MouseDownOnListBox">
In Code:
private void MouseDownOnListBox(object sender, MouseButtonEventArgs e)
{
if (e.ChangedButton == MouseButton.Right)
{
//Display your context menu
}
}
If you are using PreviewMouseDown on a list, when you click anywhere on the list, this event will be triggered first.

How to create a winform with buttons that will never attract keyboard focus

I have a few textboxes on my winform. I have a few buttons on it too. Now when I am typing on one such textbox and clicks a button, then the input focus is lost from the textbox and the button gets the input keyboard focus. That is, the cursor is lost from the textbox the moment we click the button. I dont want this behavior. I want my textbox to retain the cursor within even when I click the button.
The real situation is that I am having textbox and numeric buttons to be only used from touchscreen.
Try creating your own button control that inherits from the standard one but turns off the Selectable style:
public class ButtonEx : Button {
public ButtonEx() {
this.SetStyle(ControlStyles.Selectable, false);
}
}
In your button click event handler(s), explicitly set focus to some other control. Pick any control that you believe would be sensible to gain focus after the button is pressed. For example, set focus to a TextBox, using code like this:
textBox1.Focus();
This will prevent your button from gaining focus when a button is clicked.
In addition, set your button's TabStop property to false.
The other answers suggesting you set the CanFocus property to false won't work because that property is read-only for buttons.
You could set focus to the text box on buttons click event handler like this:
private void Button_Click(...)
{
FocusTextBox();
// Do things...
}
private void FocusTextBox()
{
textBox.Focus();
}
Create custom Button class with Focusable property, set Focusable to false
public class ButtonEx : Button
{
[DefaultValue(true)]
public bool Focusable
{
get { return GetStyle(ControlStyles.Selectable); }
set { SetStyle(ControlStyles.Selectable, value); }
}
}

WPF Default Button command not triggering binding in textbox

I have a search screen with some textboxes and a Search button as the default. If I type in a textbox and I CLICK the button, everything's great. But if I press enter within a text box, the button command fires but the binding on whatever text box I was in does NOT fire and so my criteria doesn't make it to the view model to get filtered on.
I know one fix is to set the bindings on the text boxes to PropertyChanged, but this seems like way overkill. I might have logic in the viewmodel doing stuff and I don't want that to trigger on every single keystroke.
What I really want is a way for the button itself to either trigger a focus change or somehow trigger binding. Or to have the textbox trigger binding if focus is lost OR I press enter OR a command is executed from anywhere
One way to do this is with a BindingGroup.
http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.bindinggroup.aspx
If your TextBox(es) and Button are both contained within a Grid (for example), you would add a BindingGroup like this:
<Grid>
<Grid.BindingGroup>
<BindingGroup Name="bindingGroup1"/>
</Grid.BindingGroup>
Then you could add a Click event handler to your button and call CommitEdit() on the BindingGroup (which the Button and TextBox inherit from the Grid):
private void button1_Click(object sender, RoutedEventArgs e)
{
(sender as FrameworkElement).BindingGroup.CommitEdit();
}
The Button.Click event fires before the CommandBinding, so any databound TextBox or any other databound controls within that BindingGroup should be updated before your view model command gets executed.
I've had the exact scenario you just mentioned. The trick I use is an attached behavior that sits on a control and listens for the PreviewKeyDown event. It checks if enter is being pressed. If so it forces the control to lose focus, thus causing the binding to fire before the command executes.
A simpler approach (rather than using a binding group) is to use the default button's click event to set the focus to itself. As this happens before the command is executed it means the ViewModel is updated in time.
private void button1_Click(object sender, RoutedEventArgs e)
{
(sender as Button).Focus()
}
And if you really hate code behind, you could always write an attached property...

WPF combobox-like custom control

I would like to create custom control that will look like standard WPF ComboBox, but instead of instead of having an ItemsPresenter in the popup there will be another custom control. So, I created a new class that derives from System.Windows.Controls.Control, added a IsDropDownOpen property and created a style that is actually a copy of default ComboBox style (main idea is that the Popup.IsOpen and ToggleButton.IsPressed properties are bound to the IsDropDownOpen property of the control).
The problem is that the Popup is not closed when I click outside of the control.
I took a look at the ComboBox class in the Reflector and found out that ComboBox used some logic to update the IsDropDownOpen property when it loses mouse capture. But that code uses some internal classes. Is there any alternative way to determine if the user clicked outside of the control and close the Popup?
UPD: I didn't find the way to attach a file to post, so I uploaded sample project here
There is a custom control that looks like ComboBox, but it has a TreeView in a popup. When you open popup and click outside of the control it closes automatically, but if you open popup, expand 'Item2' and then click outside the popup isn't closed. The question is how to fix this?
There is the Control.LostFocus event, maybe handling that would be sufficient for this.
This code solves the problem.
In the static contructor:
EventManager.RegisterClassHandler(typeof(CustomComboBox), Mouse.LostMouseCaptureEvent, new MouseEventHandler(OnMouseCaptureLost));
Event handler implementation:
private void OnMouseCaptureLost(object sender, MouseEventArgs e)
{
if (Mouse.Captured != _container)
{
if (e.OriginalSource != _container)
{
Mouse.Capture(_container, CaptureMode.SubTree);
e.Handled = true;
}
}
}

Can't set focus to a child of UserControl

I have a UserControl which contains a TextBox. When my main window loads I want to set the focus to this textbox so I added Focusable="True" GotFocus="UC_GotFocus" to the UserControls definition and FocusManager.FocusedElement="{Binding ElementName=login}" to my main windows definition. In the UC_GotFocus method i simply call .Focus() on the control i want to focus on but this doesn't work.
All i need to do is have a TextBox in a UserControl receive focus when the application starts.
Any help would be appreciated, thanks.
I recently fixed this problem for a login splash screen that is being displayed via a storyboard when the main window is first loaded.
I believe there were two keys to the fix. One was to make the containing element a focus scope. The other was to handle the Storyboard Completed event for the storyboard that was triggered by the window being loaded.
This storyboard makes the username and password canvas visible and then fades into being 100% opaque. The key is that the username control was not visible until the storyboard ran and therefore that control could not get keyboard focus until it was visible. What threw me off for awhile was that it had "focus" (i.e. focus was true, but as it turns out this was only logical focus) and I did not know that WPF had the concept of both logical and keyboard focus until reading Kent Boogaart's answer and looking at Microsoft's WPF link text
Once I did that the solution for my particular problem was straightforward:
1) Make the containing element a focus scope
<Canvas FocusManager.IsFocusScope="True" Visibility="Collapsed">
<TextBox x:Name="m_uxUsername" AcceptsTab="False" AcceptsReturn="False">
</TextBox>
</Canvas>
2) Attach a Completed Event Handler to the Storyboard
<Storyboard x:Key="Splash Screen" Completed="UserNamePassword_Storyboard_Completed">
...
</Storyboard>
and
3) Set my username TextBox to have the keyboard focus in the storyboard completed event handler.
void UserNamePassword_Storyboard_Completed(object sender, EventArgs e)
{
m_uxUsername.Focus();
}
Note that calling item.Focus() results in the call Keyboard.Focus(this), so you don't need to call this explicitly. See this question about the difference between Keyboard.Focus(item) and item.Focus.
Its stupid but it works:
Pop a thread that waits a while then comes back and sets the focus you want. It even works within the context of an element host.
private void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
System.Threading.ThreadPool.QueueUserWorkItem(
(a) =>
{
System.Threading.Thread.Sleep(100);
someUiElementThatWantsFocus.Dispatcher.Invoke(
new Action(() =>
{
someUiElementThatWantsFocus.Focus();
}));
}
);
}
Just recently I had a list-box that housed some TextBlocks. I wanted to be able to double click on the text block and have it turn into a TextBox, then focus on it and select all the text so the user could just start typing the new name (Akin to Adobe Layers)
Anyway, I was doing this with an event and it just wasn't working. The magic bullet for me here was making sure that I set the event to handled. I figure it was setting focus, but as soon as the event went down the path it was switching the logical focus.
The moral of the story is, make sure you're marking the event as handled, that might be your issue.
“When setting initial focus at application startup, the element to
receive focus must be connected to a PresentationSource and the
element must have Focusable and IsVisible set to true. The recommended
place to set initial focus is in the Loaded event handler"
(MSDN)
Simply add a "Loaded" event handler in the constructor of your Window (or Control), and in that event handler call the Focus() method on the target control.
public MyWindow() {
InitializeComponent();
this.Loaded += new RoutedEventHandler(MyWindow_Loaded);
}
void MyWindow_Loaded(object sender, RoutedEventArgs e) {
textBox.Focus();
}
since i tried a fuzquat's solution and found it the most generic one, i thought i'd share a different version, since some complained about it looking messy. so here it is:
casted.Dispatcher.BeginInvoke(new Action<UIElement>(x =>
{
x.Focus();
}), DispatcherPriority.ApplicationIdle, casted);
no Thread.Sleep, no ThreadPool. Clean enough i hope.
UPDATE:
Since people seem to like pretty code:
public static class WpfExtensions
{
public static void BeginInvoke<T>(this T element, Action<T> action, DispatcherPriority priority = DispatcherPriority.ApplicationIdle) where T : UIElement
{
element.Dispatcher.BeginInvoke(priority, action);
}
}
now you can call it like this:
child.BeginInvoke(d => d.Focus());
WPF supports two different flavors of focus:
Keyboard focus
Logical focus
The FocusedElement property gets or sets logical focus within a focus scope. I suspect your TextBox does have logical focus, but its containing focus scope is not the active focus scope. Ergo, it does not have keyboard focus.
So the question is, do you have multiple focus scopes in your visual tree?
I found a good series of blog posts on WPF focus.
Part 1: It’s Basically Focus
Part 2: Changing WPF focus in code
Part 3: Shifting focus to the first available element in WPF
They are all good to read, but the 3rd part specifically deals with setting focus to a UI element in a UserControl.
Set your user control to Focusable="True" (XAML)
Handle the GotFocus event on your control and call yourTextBox.Focus()
Handle the Loaded event on your window and call yourControl.Focus()
I have a sample app running with this solution as I type. If this does not work for you, there must be something specific to your app or environment that causes the problem. In your original question, I think the binding is causing the problem.
I hope this helps.
After having a 'WPF Initial Focus Nightmare' and based on some answers on stack, the following proved for me to be the best solution.
First, add your App.xaml OnStartup() the followings:
EventManager.RegisterClassHandler(typeof(Window), Window.LoadedEvent,
new RoutedEventHandler(WindowLoaded));
Then add the 'WindowLoaded' event also in App.xaml :
void WindowLoaded(object sender, RoutedEventArgs e)
{
var window = e.Source as Window;
System.Threading.Thread.Sleep(100);
window.Dispatcher.Invoke(
new Action(() =>
{
window.MoveFocus(new TraversalRequest(FocusNavigationDirection.First));
}));
}
The threading issue must be use as WPF initial focus mostly fails due to some framework race conditions.
I found the following solution best as it is used globally for the whole app.
Hope it helps...
Oran
I converted fuzquat's answer to an extension method. I'm using this instead of Focus() where Focus() did not work.
using System;
using System.Threading;
using System.Windows;
namespace YourProject.Extensions
{
public static class UIElementExtension
{
public static void WaitAndFocus(this UIElement element, int ms = 100)
{
ThreadPool.QueueUserWorkItem(f =>
{
Thread.Sleep(ms);
element.Dispatcher.Invoke(new Action(() =>
{
element.Focus();
}));
});
}
}
}
I've noticed a focus issue specifically related to hosting WPF UserControls within ElementHosts which are contained within a Form that is set as an MDI child via the MdiParent property.
I'm not sure if this is the same issue others are experiencing but you dig into the details by following the link below.
Issue with setting focus within a WPF UserControl hosted within an ElementHost in a WindowsForms child MDI form
I don't like solutions with setting another tab scope for UserControl. In that case, you will have two different carets when navigating by keyboard: on the window and the another - inside user control. My solution is simply to redirect focus from user control to inner child control. Set user control focusable (because by default its false):
<UserControl ..... Focusable="True">
and override focus events handlers in code-behind:
protected override void OnGotFocus(RoutedEventArgs e)
{
base.OnGotFocus(e);
MyTextBox.Focus();
}
protected override void OnGotKeyboardFocus(KeyboardFocusChangedEventArgs e)
{
base.OnGotKeyboardFocus(e);
Keyboard.Focus(MyTextBox);
}
What did the trick for me was the FocusManager.FocusedElement attribute. I first tried to set it on the UserControl, but it didn't work.
So I tried putting it on the UserControl's first child instead:
<UserControl x:Class="WpfApplication3.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid FocusManager.FocusedElement="{Binding ElementName=MyTextBox, Mode=OneWay}">
<TextBox x:Name="MyTextBox"/>
</Grid>
... and it worked! :)
I have user control - stack panel with two text boxes.The text boxes were added in contructor, not in the xaml. When i try to focus first text box, nothing happend.
The siggestion with Loaded event fix my problem. Just called control.Focus() in Loaded event and everthing.
Assuming you want to set focus for Username textbox, thus user can type in directly every time it shows up.
In Constructor of your control:
this.Loaded += (sender, e) => Keyboard.Focus(txtUsername);
After trying combinations of the suggestions above, I was able to reliably assign focus to a desired text box on a child UserControl with the following. Basically, give focus to the child control and have the child UserControl give focus to its TextBox. The TextBox's focus statement returned true by itself, however did not yield the desired result until the UserControl was given focus as well. I should also note that the UserControl was unable to request focus for itself and had to be given by the Window.
For brevity I left out registering the Loaded events on the Window and UserControl.
Window
private void OnWindowLoaded(object sender, RoutedEventArgs e)
{
ControlXYZ.Focus();
}
UserControl
private void OnControlLoaded(object sender, RoutedEventArgs e)
{
TextBoxXYZ.Focus();
}
I set it in the PageLoaded() or control loaded, but then I'm calling WCF async service and doing stuff that seems to lose the focus. I have to to set it at the end of all the stuff I do. That's fine and all, but sometimes I make changes to the code and then I forget that I'm also setting the cursor.
I had same problem with setting keyboard focus to canvas in WPF user control.
My solution
In XAML set element to Focusable="True"
In element_mousemove event create simple check:
if(!element.IsKeyBoardFocused)
element.Focus();
In my case it works fine.

Resources