c# - 将尺寸较小的网格内的大矩形居中(并且 ClipToBounds 不起作用)

标签 c# .net wpf xaml

我试图在高度受限的网格中心放置一个矩形,如下所示:

<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>

我希望它看起来像这样:

enter image description here

但它看起来像这样:

enter image description here

我知道我的子矩形更大,它的剪辑是可以理解的,但是,我的 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.LeftCanvas.Top 部分看出的那样)它有点骇人听闻。您可以通过绑定(bind)到 CanvasActualWidth 并使用一个 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/

相关文章:

c# - 在 Windows C# 中查找列中最后使用的行

c# - 单项字典

c# - 使用 BinaryReader 读取大文件(>1 GB)时,最佳缓冲区大小是多少?

.net - 在 DataGrid 中显示二维数组

Caliburn Micro 中的 WPF 上下文菜单

c# - 在 .NET 中通过线路移动对象时哪种方法最有效?

c# - 使用 MSBuild,我可以签署一个在文件中指定密码的应用程序吗?

.net - MVC2 中隐藏字段的替代方案

.net - 初始配置后将 Enrich.WithProperty 添加到 serilog 全局记录器

c# - 解析对象中的路径以提取其中的特定文件夹