This repository has been archived by the owner on Nov 1, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 49
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
664d62d
commit 9711f81
Showing
1 changed file
with
59 additions
and
0 deletions.
There are no files selected for viewing
59 changes: 59 additions & 0 deletions
59
src/Avalonia.Xaml.Interactions.Custom/HideFlyoutOnClickBehavior.cs
This file contains 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
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(); | ||
} | ||
} |