Return keyboard focus - wpf

I have an application where the main window contains a user control, and inside that user control are items stored in an ItemsControl. Each item can be removed by clicking an 'x' button.
The problem I am facing is that although the Keyboard focus is initially set to the user control, when you remove an item, focus is then transferred to the main window, instead of back to the user control?
Is there a way I can fix this without having to add code behind to manually store/retrieve/set focus after the click?
I have lots of these buttons within my application and I'm trying to avoid having to add code all over the place to manage returning the Focus.
I have created a very simple example to show the issue :
<UserControl x:Class="WpfApp28.MyControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid Width="300">
<StackPanel>
<ItemsControl ItemsSource="{Binding}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<TextBlock Text="{Binding}" />
<Button Content="x"
Width="20"
HorizontalAlignment="Right"
VerticalAlignment="Center"
Click="Button_Click" />
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</Grid>
</UserControl>
public partial class MyControl : UserControl
{
public MyControl()
{
InitializeComponent();
Focusable = true;
Loaded += MyControl_Loaded;
}
private void MyControl_Loaded(object sender, RoutedEventArgs e)
{
Keyboard.Focus(this);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if (sender is FrameworkElement fe && fe.DataContext is string item)
{
(DataContext as ObservableCollection<string>).Remove(item);
}
}
}
<Window x:Class="WpfApp28.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApp28"
Title="MainWindow" Height="450" Width="800">
<local:MyControl DataContext="{Binding Items}" />
public partial class MainWindow : Window
{
public ObservableCollection<string> Items { get; } = new ObservableCollection<string>();
public MainWindow()
{
Items.Add("hello");
Items.Add("there");
Items.Add("world");
DataContext = this;
InitializeComponent();
DispatcherTimer t = new DispatcherTimer();
t.Interval = TimeSpan.FromMilliseconds(250);
t.Tick += T_Tick;
t.Start();
}
private void T_Tick(object? sender, EventArgs e)
{
Title = Keyboard.FocusedElement?.GetType().ToString() ?? "NULL";
}
}

The reason that the keyboard focus moves to the hosting Window is obvious once you understand how WPF handles focus. It's important to know that WPF uses scopes in which the focus traverses the elements.
There can be multiple focus scopes allowing multiple elements to remain focused simultaneously.
By default, the hosting Window defines a focus scope. Since it is the only focus scope, it is global (the scope of the complete visual tree).
What happens in your code in short:
The Button receives the focus via mouse click
The click handler removes the clicked item and therefore the clicked Button from the visual tree
WPF moves focus back to the focus scope root, which is the MainWindow in your case
You have multiple options to prevent the focus from being moved back to the focus root. Some involve code-behind.
The following examples show how to move the focus back to the parent UserControl. But it could be any element as well:
You can configure the Button (the element that "steals" the current focus) to be not focusable. This only works if the UserControl is already focused:
<DataTemplate>
<Button Content="x"
Focusable="False" />
</DataTemplate>
You can introduce a new focus scope. Since you want the UserControl itself to be focused, you must choose the root element of the UserControl. You can achieve this by using the FocusManager helper class:
<UserControl>
<Grid x:Name="RootPanel"
FocusManager.IsFocusScope="True"
Width="300">
</Grid>
</UserControl>
You can of course register a Button.Click handler or preferably a routed command to move the focus back to the UserControl explicitly. A routed command can be more convenient in most cases. It allows to send a command parameter that makes the code-behind simpler.
Note, since Button.Click is a routed event, you can simply register a Button.Click event handler on the UserControl. This example uses the existing click handler that is used to remove the item from the ItemsControl:
UserControl.xaml
<DataTemplate>
<Button Content="x"
Click="OnButtonClick" />
</DataTemplate>
UserControl.xaml.cs
private void OnButtonClick(object sender, RoutedEventArgs)
{
/* Delete the item */
Keyboard.Focus(this);
}
Final suggested solution
To improve your code and handling of the UserControl you must definitely implement an ItemsSource dependency property and use a routed command to delete the items.
The following example uses the predefined ApplicationCommands.Delete routed command. You will notice how simple the code has become:
MyControl.xaml.cs
public partial class MyControl : UserControl
{
public IList ItemsSource
{
get => (IList)GetValue(ItemsSourceProperty);
set => SetValue(ItemsSourceProperty, value);
}
public static readonly DependencyProperty ItemsSourceProperty = DependencyProperty.Register(
"ItemsSource",
typeof(IList),
typeof(UserControl4), new PropertyMetadata(default));
public MyControl()
{
InitializeComponent();
this.Focusable = true;
}
public override void OnApplyTemplate()
=> Keyboard.Focus(this);
private void DeleteItemCommand_Executed(object sender, ExecutedRoutedEventArgs e)
=> this.ItemsSource.Remove(e.Parameter);
private void DeleteItemCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
=> e.CanExecute = this.ItemsSource.Contains(e.Parameter);
}
MyControl.xaml
<UserControl>
<UserControl.CommandBindings>
<CommandBinding Command="{x:Static ApplicationCommands.Delete}"
Executed="DeleteItemCommand_Executed"
CanExecute="DeleteItemCommand_CanExecute" />
</UserControl.CommandBindings>
<Grid x:Name="RootPanel"
FocusManager.IsFocusScope="True">
<StackPanel>
<ItemsControl ItemsSource="{Binding RelativeSource={RelativeSource AncestorType=local:UserControl4}, Path=ItemsSource}"
>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<TextBlock Text="{Binding}" />
<Button Content="x"
Command="{x:Static ApplicationCommands.Delete}"
CommandParameter="{Binding}"
Width="20"
HorizontalAlignment="Right"
VerticalAlignment="Center" />
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</Grid>
</UserControl>
MainWindow.xaml
<Window>
<MyControl ItemsSource="{Binding Items}" />
</Window>
Remarks
You should consider to use a ListBox instead of the pure ItemsControl.
ListBox is an extended ItemsControl. It will significantly improve performance and provides a ScrollViewer by default.

Related

Set focus to a usercontrol when it is made visible

I am showing a MessageBox and want the user to be able to copy the contents of the message using CTRL+C. The problem is that I can't seem to set focus to the dialog.
The MessageBox is implemented in MVVM. To show it I just make a usercontrol visible (centre screen) and disable the main view.
The copy command is implemented using a Prism DelegateCommand:
<UserControl.InputBindings>
<KeyBinding Key="C" Modifiers="Control" Command="{Binding CopyCommand}"/>
</UserControl.InputBindings>
If I tab onto on of the message box button the CopyCommand fires. However I cannot get it to work initially when the dialog is shown.
How do I get the usercontrol to accept focus or to attach the KeyBinding to the whole of the usercontrol?
Note: I need an MVVM solution as don't want any code in the code behind file.
In situations when using MVVM pattern and need to interact with the user interface, I always try to implement this solution through an attached behavior. Attached behavior is very powerful and convenient solution that fully satisfies the MVVM pattern, which can also be used in the Blend (with a pre-defined interface).
In this case, I created an attached behavior VisibleFocusBehavior, which set a IsVisibleChanged event handler, wherein the focus is set in the case of the visibility of the element.
To avoid the appearance of dotted box, when the control gets focus, I set FocusVisualStyle="{x:Null} for UserControl.
VisibleFocusBehavior
public class VisibleFocusBehavior
{
#region IsFocusEnabled Dependency Property
public static readonly DependencyProperty IsFocusEnabledProperty;
public static void SetIsFocusEnabled(DependencyObject DepObject, bool value)
{
DepObject.SetValue(IsFocusEnabledProperty, value);
}
public static bool GetIsFocusEnabled(DependencyObject DepObject)
{
return (bool)DepObject.GetValue(IsFocusEnabledProperty);
}
#endregion
#region BringToFrontBehavior Constructor
static VisibleFocusBehavior()
{
IsFocusEnabledProperty = DependencyProperty.RegisterAttached("IsFocusEnabled",
typeof(bool),
typeof(VisibleFocusBehavior),
new UIPropertyMetadata(false, IsFocusTurn));
}
#endregion
#region IsFocusTurn
private static void IsFocusTurn(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
UIElement element = sender as UIElement;
if (e.NewValue is bool && ((bool)e.NewValue) == true)
{
if (element != null)
{
element.IsVisibleChanged += new DependencyPropertyChangedEventHandler(ElementIsVisibleChanged);
}
}
}
#endregion
#region ElementIsVisibleChanged Handler
private static void ElementIsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
{
UIElement visibilityElement = sender as UIElement;
if (visibilityElement.IsVisible == true)
{
visibilityElement.Focus();
}
}
#endregion
}
Example of using
<UserControl x:Class="UserControlFocusHelp.TestUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:UserControlFocusHelp"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="300"
xmlns:AttachedBehaviors="clr-namespace:UserControlFocusHelp.AttachedBehaviors"
AttachedBehaviors:VisibleFocusBehavior.IsFocusEnabled="True"
FocusVisualStyle="{x:Null}">
<UserControl.InputBindings>
<KeyBinding Key="C"
Modifiers="Control"
Command="{Binding CopyCommand}" />
</UserControl.InputBindings>
Test window
XAML
<Grid>
<local:TestUserControl x:Name="TestUserControl"
Width="300"
Height="300"
Focusable="True"
Visibility="Collapsed" />
<Button Width="100"
Height="30"
Content="Visible"
HorizontalAlignment="Left"
Click="Button_Click" />
</Grid>
Code-behind
private void Button_Click(object sender, RoutedEventArgs e)
{
TestUserControl.Visibility = Visibility.Visible;
}
Full example is available at this link.
There is a simple way to set focus to a control. Here's an example:
<UserControl
FocusManager.FocusedElement="{Binding ElementName=txtNickname}">
<Grid>
<Grid HorizontalAlignment="Center" VerticalAlignment="Center">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<TextBox x:Name="txtNickname" Grid.Row="1" />
</Grid>
</Grid>

WPF One Way Binding broken

Im trying to bind 2 different WPF controls to the same property in the ViewModel, a CheckBox.IsChecked and an Expander.IsExpanded. The behavior I want to achieve is to have the CheckBox affect the ViewModel (and therefore the Expander as well), but not the other way bound.
Something like:
Checkbox Checked -> ViewModel property set to frue -> Expander.Expand
Checkbox Unchecked -> ViewModel property set to false -> Expander.Collapse
Expander Expanded -> Nothing else affected
Expander Collapsed -> Nothing else affected
Here's the XAML:
<Window x:Class="WpfApplication9.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Expander IsExpanded="{Binding IsChecked, Mode=OneWay}">
<Expander.Header>
<CheckBox IsChecked="{Binding IsChecked}" Content="Is Checked"/>
</Expander.Header>
<TextBlock Text="Expanded!"/>
</Expander>
</Window>
and the Code:
using System.ComponentModel;
using System.Windows;
namespace WpfApplication9
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModel();
}
}
public class ViewModel: INotifyPropertyChanged
{
private bool _isChecked;
public bool IsChecked
{
get { return _isChecked; }
set
{
_isChecked = value;
NotifyPropertyChange("IsChecked");
}
}
protected void NotifyPropertyChange(string PropertyName)
{
PropertyChanged(this, new PropertyChangedEventArgs(PropertyName));
}
public event PropertyChangedEventHandler PropertyChanged = delegate { };
}
}
Now my problem is, as soon as I click on the Expander to expand / collapse it, the Binding seems to stop working. Can anyone explain to me why this is happening and how do I achieve this? Thanks in advance!
New Answer
Discovered you could do this by setting your UpdateSourceTrigger to Explicit on your Expander. This keeps the binding as Two-Way, but never updates the Source since you're telling it not to update the source unless you explicitly tell it to.
<Expander IsExpanded="{Binding IsChecked, UpdateSourceTrigger=Explicit}">
<Expander.Header>
<CheckBox IsChecked="{Binding IsChecked}" Content="Is Checked"/>
</Expander.Header>
<TextBlock Text="Expanded!"/>
</Expander>
Leaving my old answer below so the comments make sense, and because I still feel there is no problem with view-specific code going in the code-behind of a view :)
Old Answer
Personally since this is View-Specific code, I see no problem with using a CheckBox click event to set the Expander's IsExpanded value.
private void MyCheckBox_Click(object sender, RoutedEventArgs e)
{
MyExpander.IsExpanded = ((CheckBox)sender).IsChecked.GetValueOrDefault();
}
You could make this even more generic by removing the names and navigating the Visual Tree to find the Expander associated with the CheckBox. Here's an example using some Visual Tree Helpers I built
private void CheckBox_Click(object sender, RoutedEventArgs e)
{
var chk = (CheckBox)sender;
var expander = VisualTreeHelpers.FindAncestor<Expander>(chk);
if (expander != null)
expander.IsExpanded = chk.IsChecked.GetValueOrDefault();
}
If you want the checkbox to affect the expander (but not vice versa) then bind the expander normally and use OneWayToSource on the checkbox:
<Window x:Class="WpfApplication9.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Expander IsExpanded="{Binding IsChecked}">
<Expander.Header>
<CheckBox IsChecked="{Binding IsChecked, Mode=OneWayToSource}" Content="Is Checked"/>
</Expander.Header>
<TextBlock Text="Expanded!"/>
</Expander>
</Window>
Using OneWayToSource on the checkbox will allow it to:
modify the underlying property (and therefore affect the expander, which is also bound to that property)
not be affected by other components that make changes to the underlying property
If you'd like to avoid any code-behind, you can add a degree of separation between the Expander and CheckBox states in your ViewModel:
private bool _isChecked;
public bool IsChecked
{
get { return _isChecked; }
set
{
_isChecked = value;
NotifyPropertyChange("IsChecked");
IsExpanded = value;
}
}
private bool _isExpanded;
public bool IsExpanded
{
get { return _isExpanded; }
set
{
_isExpanded = value;
NotifyPropertyChange("IsExpanded");
}
}
<Expander IsExpanded="{Binding IsExpanded}">
<Expander.Header>
<CheckBox IsChecked="{Binding IsChecked}" Content="Is Checked" x:Name="cb"/>
</Expander.Header>
<TextBlock Text="Expanded!"/>
</Expander>

TabControl fails to create first tab when using data binding

I have a tab control which items source I databind to an observable collection. I use data templates to define the visual representation of the tab's headers and content.
When I add an item to the observable collection I get a tab header but no content. When I add a second item to the observable collection I get tab headers and content for both items. So first when the second item is added to the observable collection, the content for the first tab is created. Anyone knows if this is a bug or can explain why it happens? Is there a workaround? I tried using template selector with same result. Below is sample code to reproduce.
I tested this with both .NET 3.5 and 4.0.
XAML:
<Window x:Class="TabDemo.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<StackPanel>
<Button Content="Add new tabitem" Click="OnAdd" />
<TabControl
ItemsSource="{Binding Path=Items}">
<TabControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" />
</DataTemplate>
</TabControl.ItemTemplate>
<TabControl.ContentTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" />
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
</StackPanel>
</Window>
Code behind:
public partial class Window1
{
public Window1()
{
InitializeComponent();
Items = new ObservableCollection<int>();
DataContext = this;
}
public ObservableCollection<int> Items { get; set; }
private void OnAdd(object sender, RoutedEventArgs e)
{
Items.Add(_random.Next(100));
}
private readonly Random _random = new Random();
}
If you set SelectedIndex="0" on your TabControl, it will work around this issue. I believe this has to do with a bug coercing the SelectedIndex as items are added/removed.

Dependency propery Binding Problem

Main WINDOW
<Window x:Class="dep2.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:dep2"
Title="Window1" Height="300" Width="381">
<Grid>
<local:UserControl1></local:UserControl1>
<Button Height="23" HorizontalAlignment="Right" Margin="0,0,77,36" Name="button1" VerticalAlignment="Bottom" Width="75" Click="button1_Click">Button</Button>
</Grid>
</Window>
public partial class Window1 : Window
{
UserControl1 uc = new UserControl1();
public Window1()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
uc.InfoText = "SAMPLE";
}
}
My User CONTROL
<UserControl x:Class="dep2.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="32" Width="300">
<Grid Height="30">
<StackPanel Background="LightCyan">
<TextBox Height="21" Name="textBlock1" Width="120" Text="{Binding Text}" />
</StackPanel>
</Grid>
</UserControl>
public partial class UserControl1 : UserControl
{
public string InfoText
{
get
{
return (string)GetValue(InfoTextProperty);
}
set
{
SetValue(InfoTextProperty, value);
}
}
public static readonly DependencyProperty InfoTextProperty =
DependencyProperty.Register(
"InfoText",
typeof(string),
typeof(UserControl1),
new FrameworkPropertyMetadata(
new PropertyChangedCallback(ChangeText)));
private static void ChangeText(DependencyObject source, DependencyPropertyChangedEventArgs e)
{
(source as UserControl1).UpdateText(e.NewValue.ToString());
}
private void UpdateText(string NewText)
{
textBox1.Text = NewText;
}
public UserControl1()
{
InitializeComponent();
DataContext = this;
}
}
Am getting my value in user control dependency property, but i cant able to bind my value to the text box.am using like this to bind Text="{Binding Text}" is it right,or how to bind my value in user control
i have attached my sample project here,
http://cid-08ec3041618e8ee4.skydrive.live.com/self.aspx/.SharedFavorites/dep2.rar
Can any one look and tell whats wrong in that,
everythng working well, but i cant bind the value in text box,
when u click the button u can see the passed value to usercontrol in message box, but i cant bind that value in text box.
Why????
Your code handles the callback from the dependency property and sets the text box value directly. This is not the role of this callback.
And by setting the Text property, you have lost the binding. Local property setting has a higher priority than bindings. See this blog

Is it possible to bind an Event in a Silverlight DataTemplate?

Is it possible to bind an Event in a Silverlight DataTemplate? If so, what is the best way to do it?
For example, say you've created a DataTemplate that has a Button in it, like this:
<UserControl.Resources>
<DataTemplate x:Key="MyDataTemplate" >
<Grid>
<Button Content="{Binding ButtonText}" Margin="4" />
</Grid>
</DataTemplate>
</UserControl.Resources>
Then, you apply it to a ListBox ItemTemplate, like this:
<Grid x:Name="LayoutRoot" Background="White">
<ListBox x:Name="lbListBox" ItemTemplate="{StaticResource MyDataTemplate}" />
</Grid>
If you set the ListBox's ItemSource to a list of objects of the class:
public class MyDataClass
{
public string ButtonText{ get; set; }
}
How then do you catch the button click from each button from the DataTemplate in the list? Can you use binding to bind the Click event to a method in "MyButtonClass", like this:
<UserControl.Resources>
<DataTemplate x:Key="MyDataTemplate" >
<Grid>
<Button Click="{Binding OnItemButtonClick}" Content="{Binding ButtonText}" Margin="4" />
</Grid>
</DataTemplate>
</UserControl.Resources>
Would this work? If so, what should I put in the "MyDataClass" to catch the event?
Thanks,
Jeff
There are a couple of options.
One. make a custom control that is bound the data object for that row. On that custom control add the handler for the bound object.
I dont think your binding on the click will work. Sans the Binding Statment and just declare your click to a string.
Add the handler on the page where the control is housed.
Keep in mind that if you bind this way you will only be able to work with the sender of that item (button) and it's properties. If you need to get at specific attributes on an object you maybe better off pursuing the first option.
Small Example demonstrating the functionality by adding 10 buttons to a list box with click events. HTH
DataTemplate XAML
<UserControl.Resources>
<DataTemplate x:Name="MyDataTemplate">
<Grid>
<Button Click="Button_Click" Content="{Binding ItemText}"/>
</Grid>
</DataTemplate>
</UserControl.Resources>
ListBox XAML
<ListBox x:Name="ListBoxThingee" ItemTemplate="{StaticResource MyDataTemplate}"/>
Code Behind (I just plugged this all into the page.xaml file
public class MyClass
{
public string ItemText { get; set; }
}
public partial class Page : UserControl
{
ObservableCollection<MyClass> _Items;
public Page()
{
InitializeComponent();
_Items = new ObservableCollection<MyClass>();
for (int i = 0; i < 10; i++)
{
_Items.Add(new MyClass() {ItemText= string.Format("Item - {0}", i)});
}
this.ListBoxThingee.ItemsSource = _Items;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Button _b = sender as Button;
if (_b != null)
{
string _s = _b.Content as string;
MessageBox.Show(_s);
}
}
}
What I would do is create a button that uses the command pattern for click handling. In the .NET 4 framework you can bind commands to those that exist on the view model.

Resources