Created
March 30, 2022 00:41
-
-
Save emoacht/18c28c74114b1006816ce19835d077c9 to your computer and use it in GitHub Desktop.
Attached property to move a part of TreeViewItem to the edge of TreeView with a specified left margin
This file contains hidden or 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
using System.Windows; | |
using System.Windows.Controls; | |
using System.Windows.Media; | |
public static class TreeViewHelper | |
{ | |
public static double? GetLeftMargin(DependencyObject obj) | |
{ | |
return (double?)obj.GetValue(LeftMarginProperty); | |
} | |
public static void SetLeftMargin(DependencyObject obj, double value) | |
{ | |
obj.SetValue(LeftMarginProperty, value); | |
} | |
public static readonly DependencyProperty LeftMarginProperty = | |
DependencyProperty.RegisterAttached("LeftMargin", typeof(double?), typeof(TreeViewHelper), new PropertyMetadata(null, OnValueChanged)); | |
private static void OnValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) | |
{ | |
if ((d is FrameworkElement element) && (e.NewValue is double leftMargin)) | |
{ | |
element.Loaded += (_, _) => | |
{ | |
TreeView? tv = GetTreeView(element); | |
if (tv is null) | |
return; | |
Point relativePosition = element.TransformToAncestor(tv).Transform(new Point(0, 0)); | |
element.RenderTransform = new TranslateTransform(leftMargin - relativePosition.X, 0); | |
}; | |
} | |
} | |
private static TreeView? GetTreeView(FrameworkElement element) | |
{ | |
DependencyObject test = element; | |
while (test is not null) | |
{ | |
test = VisualTreeHelper.GetParent(test); | |
if (test is TreeView tv) | |
return tv; | |
} | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment