Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use a rectangle shape as a clip in XAML

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.

like image 245
A.R. Avatar asked Apr 09 '12 15:04

A.R.


2 Answers

Try Shape.RenderedGeometry Property.

<Rectangle Width="100" Height="100"
           Clip="{Binding ElementName=ClipRect, Path=RenderedGeometry}" />
like image 147
LPL Avatar answered Nov 19 '22 13:11

LPL


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>
like image 35
Damir Arh Avatar answered Nov 19 '22 13:11

Damir Arh