Skip to content

Instantly share code, notes, and snippets.

@chuckdee68
Created June 13, 2014 19:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save chuckdee68/580cd8658c22f72dff65 to your computer and use it in GitHub Desktop.
Save chuckdee68/580cd8658c22f72dff65 to your computer and use it in GitHub Desktop.
FocusExtension - Focusing Controls in View from ViewModel using MVVM principles
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace Supporting
{
/// <summary>
/// This class registers an attached property that can be set to trigger
/// changes in focus. Basically, when the IsFocused property is set
/// to true, this extension is called in order to set the focus to the
/// calling control. In this way, it can be bound to the viewmodel
/// and focus can be set in the view without having access nor
/// knowledge of it.
/// </summary>
/// <example>
/// in viewmodel source file
///
/// public class ViewModel: INotifyPropertyChanged
/// {
/// public bool IsControlFocused { get; set; } // must implement property changed
/// }
///
/// in view xaml file
///
/// <Button Supporting:FocusExtension.IsFocused="{Binding IsControlFocused}">TestButton</Button>
/// </example>
public static class FocusExtension
{
public static bool GetIsFocused(DependencyObject depObj)
{
return (bool)depObj.GetValue(IsFocusedProperty);
}
public static void SetIsFocused(DependencyObject depObj, bool isFocused)
{
depObj.SetValue(IsFocusedProperty, isFocused);
}
public static readonly DependencyProperty IsFocusedProperty =
DependencyProperty.RegisterAttached(
"IsFocused", typeof(bool), typeof(FocusExtension),
new UIPropertyMetadata(false, OnIsFocusedPropertyChanged)
);
private static void OnIsFocusedPropertyChanged(DependencyObject depObj, DependencyPropertyChangedEventArgs args)
{
var element = (depObj as UIElement);
if (element != null)
{
// Don't care about false values.
if ((bool)args.NewValue)
{
// only focusable if these two are true
// optional to raise exception if they aren't rather than just ignoring.
if (element.Focusable && element.IsVisible)
{
element.Focus();
Keyboard.Focus(element);
FocusManager.SetFocusedElement(FocusManager.GetFocusScope(element), element);
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment