I have a TextBox
and a Button
in my view.
Now I am checking a condition upon button click and if the condition turns out to be false, displ
None of these worked for me exactly, but for the benefit of others, this is what I ended up writing based on some of the code already provided here.
Usage would be as follows:
And the implementation would be as follows:
///
/// Behavior allowing to put focus on element from the view model in a MVVM implementation.
///
public static class FocusBehavior
{
#region Dependency Properties
///
/// IsFocused dependency property.
///
public static readonly DependencyProperty IsFocusedProperty =
DependencyProperty.RegisterAttached("IsFocused", typeof(bool?),
typeof(FocusBehavior), new FrameworkPropertyMetadata(IsFocusedChanged));
///
/// Gets the IsFocused property value.
///
/// The element.
/// Value of the IsFocused property or null if not set.
public static bool? GetIsFocused(DependencyObject element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
return (bool?)element.GetValue(IsFocusedProperty);
}
///
/// Sets the IsFocused property value.
///
/// The element.
/// The value.
public static void SetIsFocused(DependencyObject element, bool? value)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
element.SetValue(IsFocusedProperty, value);
}
#endregion Dependency Properties
#region Event Handlers
///
/// Determines whether the value of the dependency property IsFocused has change.
///
/// The dependency object.
/// The instance containing the event data.
private static void IsFocusedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
// Ensure it is a FrameworkElement instance.
var fe = d as FrameworkElement;
if (fe != null && e.OldValue == null && e.NewValue != null && (bool)e.NewValue)
{
// Attach to the Loaded event to set the focus there. If we do it here it will
// be overridden by the view rendering the framework element.
fe.Loaded += FrameworkElementLoaded;
}
}
///
/// Sets the focus when the framework element is loaded and ready to receive input.
///
/// The sender.
/// The instance containing the event data.
private static void FrameworkElementLoaded(object sender, RoutedEventArgs e)
{
// Ensure it is a FrameworkElement instance.
var fe = sender as FrameworkElement;
if (fe != null)
{
// Remove the event handler registration.
fe.Loaded -= FrameworkElementLoaded;
// Set the focus to the given framework element.
fe.Focus();
// Determine if it is a text box like element.
var tb = fe as TextBoxBase;
if (tb != null)
{
// Select all text to be ready for replacement.
tb.SelectAll();
}
}
}
#endregion Event Handlers
}