2012-04-09 92 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