Skip to content

UIElement.ClipToBounds property #3111

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using Windows.UI.Xaml;
using Windows.UI.Xaml.Hosting;

namespace Microsoft.Toolkit.Uwp.UI.Extensions
{
/// <summary>
/// Provides attached dependency properties for the <see cref="Windows.UI.Xaml.UIElement"/>
/// </summary>
public static class UIElementExtensions
{
/// <summary>
/// Attached <see cref="DependencyProperty"/> that indicates whether or not the contents of the target <see cref="UIElement"/> should always be clipped to their parent's bounds.
/// </summary>
public static readonly DependencyProperty ClipToBoundsProperty = DependencyProperty.RegisterAttached("ClipToBounds", typeof(bool), typeof(UIElementExtensions), new PropertyMetadata(DependencyProperty.UnsetValue, OnClipToBoundsPropertyChanged));

/// <summary>
/// Gets the value of <see cref="ClipToBoundsProperty"/>
/// </summary>
/// <param name="element">The <see cref="UIElement"/> to read the property value from</param>
/// <returns>The <see cref="bool"/> associated with the <see cref="FrameworkElement"/></returns>.
public static bool GetClipToBounds(UIElement element)
{
return (bool)element.GetValue(ClipToBoundsProperty);
}

/// <summary>
/// Sets the value of <see cref="ClipToBoundsProperty"/>
/// </summary>
/// <param name="element">The <see cref="UIElement"/> to set the property to</param>
/// <param name="value">The new value of the attached property</param>
public static void SetClipToBounds(UIElement element, bool value)
{
element.SetValue(ClipToBoundsProperty, value);
}

private static void OnClipToBoundsPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var element = d as UIElement;

if (element is null)
{
return;
}

bool value = (bool)e.NewValue;

var visual = ElementCompositionPreview.GetElementVisual(element);

visual.Clip = value ? visual.Compositor.CreateInsetClip() : null;
}
}
}