Created
June 24, 2011 12:38
-
-
Save vegar/1044691 to your computer and use it in GitHub Desktop.
SelectAndGiveFocusToFirstElementInListBoxBehaviour - example code for StackOverflow question 6467928
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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