将一个大矩形放在尺寸较小的网格内居中(并且 ClipToBounds 不起作用)
我试图将一个矩形放置在高度受限的网格中心,如下所示:
<Grid ClipToBounds="False">
<Grid Background="LightBlue" Height="10" ClipToBounds="False" Margin="0,27,0,79">
<Rectangle Height="40" Width="20" Fill="Black" VerticalAlignment="Center" HorizontalAlignment="Center" ClipToBounds="False"/>
</Grid>
</Grid>
我期望它看起来像这样:
但它看起来像这样:
我认识我的孩子矩形更大,这是可以理解的剪辑,但是,我的 ClipToBounds 没有任何效果。经过阅读后,我发现确实 Grid 不尊重“ClipToBounds” 。
我尝试使用 Canvas,正如 Dr.Wpf 的前述文章中所建议的,但我不能似乎没有做对。
我可以做些什么来让它看起来像第一张图片,而不需要求助于 C# 代码吗?
谢谢!
I'm trying to position a rectangle in the center of a grid with a restricted height, like so:
<Grid ClipToBounds="False">
<Grid Background="LightBlue" Height="10" ClipToBounds="False" Margin="0,27,0,79">
<Rectangle Height="40" Width="20" Fill="Black" VerticalAlignment="Center" HorizontalAlignment="Center" ClipToBounds="False"/>
</Grid>
</Grid>
I've expected it to look like that:
But instead it looks like that:
I know the my child rectangle is bigger and it is understandable that it clips, however, my ClipToBounds have no effect of anything. After reading around, I found that indeed Grid does not respect "ClipToBounds".
I tried to use Canvas, as suggested in the aforementioned article by Dr.Wpf but I can't seem to get it right.
Is there anything I can do to make it look like the 1st picture, without resorting to C# code?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在这里很难确切地说出您的要求是什么。你说你用 Canvas 尝试过,但你似乎无法做到正确。什么不起作用?
我使用了这段代码:
并且能够基本上伪造您的屏幕截图的样子。但是(正如您可以从我的代码的
Canvas.Left
和Canvas.Top
部分看出的)它有点黑客。您可以通过绑定到Canvas
的ActualWidth
并使用IValueConverter
来摆脱Canvas.Left
将其转换为正确的值。编辑:
经过进一步探索,我想出了一种稍微不那么黑客化的方法。虽然嵌套让我感到畏缩,但唯一硬编码的是顶部边距,以使其垂直居中。同样,这可以通过 IValueConverter 来完成,但您不希望这样做。不幸的是,我不确定我能得到比这更好的东西。
It's a little hard to tell exactly what your requirements are here. You said you tried it witha Canvas, but you can't seem to get it right. What didn't work?
I used this code:
and was able to essentially fake what your screenshot looked like. But (as you can tell by the
Canvas.Left
andCanvas.Top
parts of my code) it is sort of hackish. You could get rid of theCanvas.Left
by binding to theActualWidth
of theCanvas
and using anIValueConverter
that converts it to the correct value.Edit:
After a little further exploration, I came up with a slightly less hackish way of doing it. Though the nesting kind of makes me cringe, the only thing hardcoded is the top margin to get it centered vertically. Again, that can be done with an
IValueConverter
, but you don't want that. I'm not sure I can get any better than this, unfortunately.