Last active
October 16, 2019 13:14
-
-
Save canton7/6131194404a232da0917800639444c7e to your computer and use it in GitHub Desktop.
Read TreeView SelectedItem
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 static class TreeViewExtensions | |
{ | |
private static readonly object initialBindingTarget = new object(); | |
public static object GetSelectedItem(DependencyObject obj) => obj.GetValue(SelectedItemProperty); | |
public static void SetSelectedItem(DependencyObject obj, object value) => obj.SetValue(SelectedItemProperty, value); | |
public static readonly DependencyProperty SelectedItemProperty = | |
DependencyProperty.RegisterAttached("SelectedItem", typeof(object), typeof(TreeViewExtensions), new FrameworkPropertyMetadata(initialBindingTarget, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, (d, e) => | |
{ | |
if (!(d is TreeView treeView)) | |
return; | |
// Trick to see if this is the first time we're set | |
if (e.OldValue == initialBindingTarget) | |
{ | |
treeView.SelectedItemChanged += SelectedItemChanged; | |
} | |
})); | |
private static void SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e) | |
{ | |
if (!(sender is TreeView treeView)) | |
return; | |
SetSelectedItem(treeView, e.NewValue); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment