Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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