Use a rectangle shape as a clip in XAML

前端 未结 2 1137
旧巷少年郎
旧巷少年郎 2021-01-18 18:04

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..

相关标签:
2条回答
  • 2021-01-18 18:22

    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>
    
    0 讨论(0)
  • 2021-01-18 18:24

    Try Shape.RenderedGeometry Property.

    <Rectangle Width="100" Height="100"
               Clip="{Binding ElementName=ClipRect, Path=RenderedGeometry}" />
    
    0 讨论(0)
提交回复
热议问题