我试图在Windows运行时中找到等效的ClipToBounds。 如果它不存在,有没有办法重新创建这种行为?
答案 0 :(得分:4)
以下是我使用的解决方案:
public class Clip
{
public static bool GetToBounds(DependencyObject depObj)
{
return (bool)depObj.GetValue(ToBoundsProperty);
}
public static void SetToBounds(DependencyObject depObj, bool clipToBounds)
{
depObj.SetValue(ToBoundsProperty, clipToBounds);
}
/// <summary>
/// Identifies the ToBounds Dependency Property.
/// <summary>
public static readonly DependencyProperty ToBoundsProperty =
DependencyProperty.RegisterAttached("ToBounds", typeof(bool),
typeof(Clip), new PropertyMetadata(false, OnToBoundsPropertyChanged));
private static void OnToBoundsPropertyChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
FrameworkElement fe = d as FrameworkElement;
if (fe != null)
{
ClipToBounds(fe);
// whenever the element which this property is attached to is loaded
// or re-sizes, we need to update its clipping geometry
fe.Loaded += new RoutedEventHandler(fe_Loaded);
fe.SizeChanged += new SizeChangedEventHandler(fe_SizeChanged);
}
}
/// <summary>
/// Creates a rectangular clipping geometry which matches the geometry of the
/// passed element
/// </summary>
private static void ClipToBounds(FrameworkElement fe)
{
if (GetToBounds(fe))
{
fe.Clip = new RectangleGeometry()
{
Rect = new Rect(0, 0, fe.ActualWidth, fe.ActualHeight)
};
}
else
{
fe.Clip = null;
}
}
static void fe_SizeChanged(object sender, SizeChangedEventArgs e)
{
ClipToBounds(sender as FrameworkElement);
}
static void fe_Loaded(object sender, RoutedEventArgs e)
{
ClipToBounds(sender as FrameworkElement);
}
}
找到它here
答案 1 :(得分:2)
这是在WinRTXamlToolkit(https://github.com/xyzzer/WinRTXamlToolkit)中实现的,它也可以作为Nuget包使用。
添加到XAML标题:
xmlns:extensions="using:WinRTXamlToolkit.Controls.Extensions"
然后,例如在XAML Canvas组件
中<Canvas extensions:FrameworkElementExtensions.ClipToBounds="True"/>
答案 2 :(得分:1)
我更喜欢&#39; Clip&#39;这里的属性是一些xaml
<Grid Width="100" Height="50">
<Grid.Clip>
<RectangleGeometry Rect="0 0 100 50"/>
</Grid.Clip>
</Grid>
&#39; Rect&#39;的参数。属性是:Rect =&#34; x y width height&#34;
希望有所帮助
问候