Skip to content

Instantly share code, notes, and snippets.

@vegar
Created June 24, 2011 12:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vegar/1044691 to your computer and use it in GitHub Desktop.
Save vegar/1044691 to your computer and use it in GitHub Desktop.
SelectAndGiveFocusToFirstElementInListBoxBehaviour - example code for StackOverflow question 6467928
public class SelectAndGiveFocusToFirstElementInListBoxBehavior
{
public static readonly DependencyProperty EnabledProperty =
DependencyProperty.RegisterAttached(
"Enabled",
typeof(bool),
typeof(SelectAndGiveFocusToFirstElementInListBoxBehavior),
new FrameworkPropertyMetadata(0, new PropertyChangedCallback(OnEnabledChanged)));
public static bool GetEnabled(ListBox listBox) {...}
public static void SetEnabled(ListBox listBox, bool value) {...}
private static void OnEnabledChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs args)
{
var listBox = dependencyObject as ListBox;
if (listBox != null)
{
ListenToItemsCollectionChange(listBox);
}
}
private static void ListenToItemsCollectionChange(ListBox listBox)
{
var collection = (INotifyCollectionChanged)listBox.Items;
collection.CollectionChanged += (sender, args) => SelectAndSetFocusToFirstElementIfEnabled(listBox);
}
private static void SelectAndSetFocusToFirstElementIfEnabled(ListBox listBox)
{
if (GetEnabled(listBox))
{
SelectAndSetFocusToFirstElement(listBox);
}
}
private static void SelectAndSetFocusToFirstElement(ListBox listBox) {...}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment