diff --git a/Microsoft.Toolkit.Uwp.UI/Extensions/ConditionalToolTip.cs b/Microsoft.Toolkit.Uwp.UI/Extensions/ConditionalToolTip.cs new file mode 100644 index 00000000000..ef13970f337 --- /dev/null +++ b/Microsoft.Toolkit.Uwp.UI/Extensions/ConditionalToolTip.cs @@ -0,0 +1,76 @@ +using Windows.UI.Xaml; +using Windows.UI.Xaml.Controls; + +namespace Microsoft.Toolkit.Uwp.UI.Extensions +{ + /// + /// Provides attached dependency properties that allow a + /// to conditionally enable or disable its tooltip. + /// + public class ConditionalToolTip : DependencyObject + { + /// + /// Attached for enabling or disabling the tooltip for a . + /// + public static readonly DependencyProperty IsToolTipEnabledProperty = DependencyProperty.RegisterAttached( + "IsToolTipEnabled", + typeof(bool), + typeof(ConditionalToolTip), + new PropertyMetadata(true, OnIsToolTipEnabledChanged)); + + /// + /// Attached for binding for the content to display in the tooltip for a . + /// + public static readonly DependencyProperty ToolTipContentProperty = DependencyProperty.RegisterAttached( + "ToolTipContent", + typeof(object), + typeof(ConditionalToolTip), + new PropertyMetadata(null, OnContentChanged)); + + /// + /// Sets the bool determining if the tooltip is enabled for the specified . + /// + /// The from which to set the associated IsToolTipEnabled value. + /// The bool value to assign. + public static void SetIsToolTipEnabled(UIElement element, bool value) => element.SetValue(IsToolTipEnabledProperty, value); + + /// + /// Gets the bool determing if the tooltip is enabled for the specified . + /// + /// The from which to get the associated IsToolTipEnabled value. + /// True if the conditional tooltip is enabled. False, otherwise. + public static bool GetIsToolTipEnabled(UIElement element) => (bool)element.GetValue(IsToolTipEnabledProperty); + + /// + /// Sets the content of the conditional tooltip associated with the specified . + /// + /// The from which to set the associated conditional tooltip content. + /// The content to assign. + public static void SetToolTipContent(UIElement element, object value) => element.SetValue(ToolTipContentProperty, value); + + /// + /// Gets the content of the conditional tooltip associated with the specified . + /// + /// The from which to get the associated conditional tooltip content. + /// The conditional tooltip's content. + public static object GetToolTipContent(UIElement element) => (object)element.GetValue(ToolTipContentProperty); + + private static void OnIsToolTipEnabledChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) + { + if (d is UIElement element) + { + ToolTipService.SetToolTip(d, e.NewValue is true + ? GetToolTipContent(element) + : null); + } + } + + private static void OnContentChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) + { + if (d is UIElement element && GetIsToolTipEnabled(element)) + { + ToolTipService.SetToolTip(d, e.NewValue); + } + } + } +}