我试图在高度受限的网格中心放置一个矩形,如下所示:
<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 does not respect "ClipToBounds" .
我尝试按照 aforementioned article 中的建议使用 Canvas由 Dr.Wpf 提供,但我似乎无法正确理解。
有什么办法可以使它看起来像第一张图片,而无需借助 C# 代码?
谢谢!
最佳答案
在此处准确说出您的要求有点困难。你说你用 Canvas 试过,但你似乎做对了。什么不起作用?
我使用了这段代码:
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="TestApp.MainWindow"
x:Name="Window"
Title="MainWindow"
Width="175" Height="170" Background="LightGray">
<Grid>
<Canvas Background="LightBlue" Height="10"
Margin="0,27,0,79" VerticalAlignment="Top">
<Rectangle Height="40" Width="20" Fill="Black"
Canvas.Left="66" Canvas.Top="-15" />
</Canvas>
</Grid>
</Window>
并且能够从根本上伪造您的屏幕截图。但是(正如您可以从我的代码的 Canvas.Left
和 Canvas.Top
部分看出的那样)它有点骇人听闻。您可以通过绑定(bind)到 Canvas
的 ActualWidth
并使用一个 IValueConverter
来摆脱 Canvas.Left
将其转换为正确的值。
编辑:
经过进一步探索,我想出了一个稍微不那么骇人听闻的方法。虽然嵌套让我感到畏缩,但唯一硬编码的是顶部边距以使其垂直居中。同样,这可以通过 IValueConverter
来完成,但您不希望这样。不幸的是,我不确定我能得到比这更好的东西。
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="WpfApplication10.MainWindow"
x:Name="Window"
Title="MainWindow"
Width="640" Height="480">
<Grid x:Name="LayoutRoot">
<Grid Background="LightBlue" Height="10" ClipToBounds="False" Margin="0,27,0,79">
<Canvas>
<Grid Width="{Binding ActualWidth, RelativeSource={RelativeSource FindAncestor, AncestorType=Canvas}}"
Height="{Binding ActualHeight, RelativeSource={RelativeSource FindAncestor, AncestorType=Canvas}}">
<Canvas HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0 -40 0 0">
<Rectangle Height="40" Width="20" Fill="Black" ClipToBounds="False"/>
</Canvas>
</Grid>
</Canvas>
</Grid>
</Grid>
</Window>
关于c# - 将尺寸较小的网格内的大矩形居中(并且 ClipToBounds 不起作用),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6091035/