创建空心边框/方形wpf

时间:2013-04-07 09:37:46

标签: wpf silverlight wpf-controls

我想在WPF / Silverlight中创建一个控件。该控件是矩形/边框,从中心是空心的。我的意图是除了矩形/边框容器内的平方区域之外的所有其他内容。有可能这样做吗?

此外,它应该能够在鼠标移动时移动此空心区域。

提前感谢大家的帮助。 This is the sample output I want

1 个答案:

答案 0 :(得分:3)

嗯,最简单的解决方案是:

<Grid Width="256" Height="256" MouseMove="UIElement_OnMouseMove">
    <Image Source="test1.jpg" Stretch="UniformToFill" />
    <Path Fill="#81808080" Stretch="Fill">
        <Path.Data>
            <CombinedGeometry GeometryCombineMode="Exclude">
                <CombinedGeometry.Geometry1>
                    <RectangleGeometry Rect="0,0,100,100" />
                </CombinedGeometry.Geometry1>
                <CombinedGeometry.Geometry2>
                    <RectangleGeometry
                        x:Name="Hole"
                        RadiusX="7"
                        RadiusY="7"
                        Rect="20,20,60,60" /> <!-- this is the hole -->
                </CombinedGeometry.Geometry2>
            </CombinedGeometry>
        </Path.Data>
    </Path> 
</Grid>

事件处理程序:

private void UIElement_OnMouseMove(object sender, MouseEventArgs e) {
    var element = (FrameworkElement) sender;
    var position = e.GetPosition(element);

    var relativeX = position.X/element.ActualWidth*100.0;
    var relativeY = position.Y/element.ActualHeight*100.0;

    Hole.Rect = new Rect(relativeX - 20, relativeY - 20, 40, 40);    
}