【问题标题】:Stretching Border in UniformGrid在 UniformGrid 中拉伸边框
【发布时间】:2026-01-19 23:10:02
【问题描述】:

我认为我的问题很标准,所以我搜索了 *,但没有找到与我有相同问题的人。

我需要通过代码填充 UniformGrid 并为 UniformGrid 内的特定元素添加一些边框,因此最终它看起来像棋盘格。 使用 Rectangles 作为我的 UniformGrid 的子项,我部分得到了我需要的东西,但是 Rectangles Strokes 不能单独设置。

因此尝试使用边框作为我的孩子,但似乎 VerticalAlignment 和 Horizo​​ntalAlignment“拉伸”在 UniformGrid 内不起作用。

我的代码:

...

myUniformGrid.Rows = 2;
myUniformGrid.Columns = 2;    


var myBorder = new Border()
{
    VerticalAlignment = VerticalAlignment.Stretch,
    HorizontalAlignment = HorizontalAlignment.Stretch,
    BorderBrush = new SolidColorBrush(Color.FromArgb(48,0,0,0)),
    BorderThickness = new Thickness(1,1,1,1)
};

// This is called 4 times in a loop (with different objects), it's for signalisation 
// that i have 4 borders in my UniformGrid.
myUniformGrid.Children.Add(myBorder);

当我运行它时,UniformGrid 不显示我的边框。

感谢您的帮助。

【问题讨论】:

  • 某处必须设置样式。或者您的统一网格不会自行拉伸以填充其父级。此代码完美运行。

标签: c# wpf


【解决方案1】:

您的边框没有显示,因为您设置了BorderBrush,但没有设置BorderThickness,那时它为零。您还可以使用内置的Colors 类型来简化您的代码。不需要手动设置对齐方式,默认会拉伸。

var myBorder = new Border { BorderBrush = new SolidColorBrush(Colors.Black), BorderThickness = new Thickness(1)};

如果你想改用Rectangle,你必须设置StrokeStrokeThickness

var myRectangle = new Rectangle { Stroke = new SolidColorBrush(Colors.Black), StrokeThickness = 1.0};

将同一个实例多次添加到您的UniformGrid 将不起作用。您必须创建四个不同的边框或矩形实例。它们按照添加到 Children 集合的顺序从左到右、从上到下插入到您的网格中。

【讨论】:

  • 好吧,我得说,我提出的问题有点草率。设置了厚度,我只是没有使用它我的问题:/ 并且评论只是为了防止编写循环。抱歉,我会编辑问题
  • @Febertson 当时UniformGrid 使用或样式的方式一定有问题。我对其进行了测试,它在我的网站上运行。
  • 嗯,我今天不能再试了,我明天再试,告诉你! :)
【解决方案2】:

尝试在 XAML 而不是代码中声明边框外观,看看这是否适合您:

<UniformGrid Height="20" Name="myUniformGrid" Rows="2" Columns="2">
    <UniformGrid.Resources>
        <Style TargetType="Border">
            <Setter Property="BorderBrush" Value="HotPink"/>
            <Setter Property="BorderThickness" Value="2,2,2,2"/>
        </Style>
    </UniformGrid.Resources>
</UniformGrid>

这绝对可以。注意这样做时不要在代码中设置参数:

myUniformGrid.Children.Add(new Border());

【讨论】:

    最近更新 更多