Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/maven/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在XAML中使用矩形形状作为剪辑_C#_Wpf_Silverlight_Xaml_Expression - Fatal编程技术网

C# 在XAML中使用矩形形状作为剪辑

C# 在XAML中使用矩形形状作为剪辑,c#,wpf,silverlight,xaml,expression,C#,Wpf,Silverlight,Xaml,Expression,是否有一种方法可以使用普通矩形(形状)作为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 f

是否有一种方法可以使用普通矩形(形状)作为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>


我知道我可以使用“矩形几何”类型的方法,但我更感兴趣的是上述代码的解决方案。

ClipRect.DefiningGeometry
nd
ClipRect.RenderedGeometry
仅包含
RadiusX
RadiusY
值,但不包含
Rect

我不确定您到底想要实现什么(从您的示例中我不清楚),但您可以编写一个
IValueConverter
,它将从引用的
矩形中提取您需要的信息:

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>

试试看



在我的示例中,我试图用一个矩形来剪裁另一个矩形。我试图避免转换器/变通方法。@A.R.避免转换器(您称之为变通方法)的唯一方法是找到包含您所需信息的。如果没有它,您将无法避免至少一些代码。我发现转换器最不“邪恶”,因为它本质上仍然是标记。
<Rectangle Width="100" Height="100"
           Clip="{Binding ElementName=ClipRect, Path=RenderedGeometry}" />