Use a rectangle shape as a clip in XAML

痴心易碎 提交于 2019-12-19 19:49:20

问题


Is there a way that I can use a normal Rectangle (shape) as part of a clip for another object in XAML. It seems like I should be able to, but the solution is eluding me..

<Canvas>

        <Rectangle Name="ClipRect" RadiusY="10" RadiusX="10" Stroke="Black" StrokeThickness="0" Width="32.4" Height="164"/>

<!-- This is the part that I cant quite figure out.... -->
<Rectangle Width="100" Height="100" Clip={Binding ElementName=ClipRect, Path="??"/>

</Canvas>

I know that I can use a 'RectangleGeometry' type approach, but I am more interested in the solution in terms of the code presented above.


回答1:


Try Shape.RenderedGeometry Property.

<Rectangle Width="100" Height="100"
           Clip="{Binding ElementName=ClipRect, Path=RenderedGeometry}" />



回答2:


ClipRect.DefiningGeometry nd ClipRect.RenderedGeometry contain only the RadiusX and RadiusY values but not also Rect.

I'm not sure what exactly you want to achieve (it's not clear to me from your sample) but you could write an IValueConverter which would extract the info you require from the referenced Rectangle:

public class RectangleToGeometryConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        var rect = value as Rectangle;

        if (rect == null || targetType != typeof(Geometry))
        {
            return null;
        }

        return new RectangleGeometry(new Rect(new Size(rect.Width, rect.Height)))
        { 
            RadiusX = rect.RadiusX, 
            RadiusY = rect.RadiusY 
        };
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

You would then use this converter in your binding definition:

<Rectangle Width="100" Height="100" 
            Clip="{Binding ElementName=ClipRect, Converter={StaticResource RectangleToGeometryConverter}}">

Of course you need to add the converter to your resources first:

<Window.Resources>
    <local:RectangleToGeometryConverter x:Key="RectangleToGeometryConverter" />
</Window.Resources>


来源:https://stackoverflow.com/questions/10075262/use-a-rectangle-shape-as-a-clip-in-xaml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!