BindTagToVisualRootDataContextBehavior.cs 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. using System;
  2. using System.Reactive.Disposables;
  3. using Avalonia.Controls;
  4. using Avalonia.VisualTree;
  5. namespace Avalonia.Xaml.Interactions.Custom;
  6. /// <summary>
  7. /// Binds AssociatedObject object Tag property to root visual DataContext.
  8. /// </summary>
  9. public class BindTagToVisualRootDataContextBehavior : DisposingBehavior<Control>
  10. {
  11. /// <summary>
  12. ///
  13. /// </summary>
  14. /// <param name="disposables"></param>
  15. /// <exception cref="NotImplementedException"></exception>
  16. protected override void OnAttached(CompositeDisposable disposables)
  17. {
  18. var visualRoot = (Control?)AssociatedObject?.GetVisualRoot();
  19. if (visualRoot is not null)
  20. {
  21. var disposable = BindDataContextToTag(visualRoot, AssociatedObject);
  22. disposables.Add(disposable);
  23. }
  24. }
  25. private static IDisposable BindDataContextToTag(Control source, Control? target)
  26. {
  27. if (source is null)
  28. {
  29. throw new ArgumentNullException(nameof(source));
  30. }
  31. if (target is null)
  32. {
  33. throw new ArgumentNullException(nameof(target));
  34. }
  35. return target.Bind(
  36. Control.TagProperty,
  37. source.GetObservable(StyledElement.DataContextProperty));
  38. }
  39. }