Skip to content

Instantly share code, notes, and snippets.

@canton7
Last active October 16, 2019 13:14
Show Gist options
  • Save canton7/6131194404a232da0917800639444c7e to your computer and use it in GitHub Desktop.
Save canton7/6131194404a232da0917800639444c7e to your computer and use it in GitHub Desktop.
Read TreeView SelectedItem
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