2012-04-09 47 views
4

是否有一种方法可以将常规Rectangle(形状)用作XAML中另一个对象的剪辑的一部分。好像我应该是可以的,但解决方案是躲避我。在XAML中使用矩形形状作为剪辑

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

我知道,我可以用一个“RectangleGeometry”式的做法,但我更感兴趣的是解决方案中的代码的条款如上所述。

+0

看看http://stackoverflow.com/questions/1321740/wpf-how-to-show-only-part-of-big-canvas – 2012-04-09 15:28:57

回答

1

ClipRect.DefiningGeometry nd ClipRect.RenderedGeometry仅包含RadiusXRadiusY值,但不包括Rect

我不知道究竟你要实现(这不是很清楚,我从你的样品)什么,但你可以写一个IValueConverter这将提取您从引用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(); 
    } 
} 

这样,你会在你的绑定定义中使用该转换器:

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

当然,你需要转换器第一次添加到您的资源:

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

在我的例子,我想剪辑一个矩形与另一个。我试图避免转换器/解决方法。 – 2012-04-09 15:49:26

+0

@ A.R。避免使用转换器的唯一方法(在您称之为变通方法时)是找到一个[Rectangle属性](http://msdn.microsoft.com/zh-cn/library/system.windows.shapes.rectangle_properties.aspx)它包含您需要的信息。如果[RenderedGeometry](http://msdn.microsoft.com/en-us/library/system.windows.shapes.rectangle.renderedgeometry.aspx)和[DefiningGeometry](http://msdn.microsoft.com/en-我们/图书馆/ system.windows.shapes.shape.defininggeometry.aspx)没有它,你将无法避免至少一些代码。我发现一个转换器至少是“邪恶”,因为它本质上仍然是标记。 – 2012-04-09 17:20:26

+0

没有某种“解决方法”就无法完成。 – Denis 2012-04-09 19:01:30