Skip to content
This repository has been archived by the owner on Nov 1, 2024. It is now read-only.

Commit

Permalink
Create HideFlyoutOnClickBehavior.cs
Browse files Browse the repository at this point in the history
  • Loading branch information
wieslawsoltes committed Apr 16, 2024
1 parent 664d62d commit 9711f81
Showing 1 changed file with 59 additions and 0 deletions.
59 changes: 59 additions & 0 deletions src/Avalonia.Xaml.Interactions.Custom/HideFlyoutOnClickBehavior.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
using System;
using System.Reactive.Linq;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Interactivity;
using Avalonia.VisualTree;
using Avalonia.Xaml.Interactivity;

namespace Avalonia.Xaml.Interactions.Custom;

/// <summary>
///
/// </summary>
public class HideFlyoutOnClickBehavior : Behavior<RadioButton>
{
private IDisposable? _subscription;

/// <summary>
///
/// </summary>
protected override void OnAttachedToVisualTree()
{
base.OnAttachedToVisualTree();

if (AssociatedObject == null)
{
return;
}

var fp = AssociatedObject.FindAncestorOfType<FlyoutPresenter>();

if (fp?.Parent is not Popup popup)
{
return;
}

_subscription = Observable
.FromEventPattern<RoutedEventArgs>(handler => AssociatedObject.Click += handler, handler => AssociatedObject.Click -= handler)
.Do(_ =>
{
// Execute Command if any before closing. Otherwise, it won't execute because Close will destroy the associated object before Click can execute it.
if (AssociatedObject.Command != null && AssociatedObject.IsEnabled)
{
AssociatedObject.Command.Execute(AssociatedObject.CommandParameter);
}
popup.Close();
})
.Subscribe();
}

/// <summary>
///
/// </summary>
protected override void OnDetachedFromVisualTree()
{
base.OnDetachedFromVisualTree();
_subscription?.Dispose();
}
}

0 comments on commit 9711f81

Please sign in to comment.