Popup helper for close it on click
If you want to close a Popup automatically when click on it or children, use this helper
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
public class PopupHelper { #region CloseOnClick [AttachedPropertyBrowsableForType(typeof(Popup))] public static bool GetCloseOnClick(DependencyObject obj) => (bool)obj.GetValue(CloseOnClickProperty); public static void SetCloseOnClick(DependencyObject obj, bool value) => obj.SetValue(CloseOnClickProperty, value); public static readonly DependencyProperty CloseOnClickProperty = DependencyProperty.RegisterAttached("CloseOnClick", typeof(bool), typeof(PopupHelper), new PropertyMetadata(false , (ss, ee) => { if (ss is Popup popup) { var m = new RoutedEventHandler((sender, e) => { popup.IsOpen = false; }); popup.AddHandler(Mouse.PreviewMouseUpEvent, m); } else throw new InvalidOperationException("only for popup"); })); #endregion } |
and
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
<ToggleButton x:Name="tb" local:ToggleButtonHelper.BindingPopup="{Binding ElementName=popup}" Content="alpha" Height="32" Width="150" Margin="10,37,0,0" VerticalAlignment="Top" HorizontalAlignment="Left" /> <Popup x:Name="popup" StaysOpen="false" local:PopupHelper.CloseOnClick="true" PlacementTarget="{Binding ElementName=tb}" Width="{Binding ActualWidth, ElementName=tb}"> <Border Background="White" BorderBrush="Black" BorderThickness="1" Padding="5"> <ListBox SelectedItem="{Binding Selected}" BorderThickness="0"> <ListBoxItem Content="Alpha" /> <ListBoxItem Content="Beta" /> <ListBoxItem Content="Gamma" /> <ListBoxItem Content="Zota" /> </ListBox> </Border> </Popup> |
see http://ultimatespy.sytes.net/wpf/index.php/2022/03/30/togglebutton-to-control-popup/ for ToggleButtonHelper
Categories: Non classé
Commentaires récents