gpt4 book ai didi

c# - WPF网格白色条纹

转载 作者:行者123 更新时间:2023-11-30 14:46:02 26 4
gpt4 key购买 nike

我有一个 Grid,里面有很多按钮。这些按钮应该是无缝连接的。在大多数情况下,这实际上是可行的,但有时在网格的列/行之间会出现白色条纹:

white stripes in image

我正在通过这样的代码将按钮添加到网格中(对于非最小代码我很抱歉,但我真的不知道这里可能有什么相关):

public partial class MainWindow
{
private int _xCount;
private int _yCount;

public MainWindow ()
{
InitializeComponent ();

SetSize (40, 40);
}

public void SetSize (int x, int y)
{
_xCount = x;
_yCount = y;

Grid.ColumnDefinitions.Clear ();
Grid.RowDefinitions.Clear ();

for (var i = 0; i < x; i++)
Grid.ColumnDefinitions.Add (new ColumnDefinition {Width = new GridLength (100, GridUnitType.Star)});
for (var i = 0; i < y; i++)
Grid.RowDefinitions.Add (new RowDefinition {Height = new GridLength (100, GridUnitType.Star)});

for (var xI = 0; xI < x; xI++)
for (var yI = 0; yI < y; yI++)
{
var button = new Button
{
BorderThickness = new Thickness (1),
BorderBrush = Brushes.Gray,
Foreground = Brushes.DarkGray,
Content = "",
Background = Brushes.DarkGray
};

Grid.Children.Add (button);
Grid.SetColumn (button, xI);
Grid.SetRow (button, yI);
}

SetButtonSizes ();
}

private void SetButtonSizes ()
{
var gridWidth = Grid.Width;
var gridHeight = Grid.Height;

var buttonWidth = gridWidth / _xCount;
var buttonHeight = gridHeight / _yCount;

foreach (var button in Grid.Children)
{
((Button) button).Width = buttonWidth;
((Button) button).Height = buttonHeight;
}
}

protected override void OnRenderSizeChanged (SizeChangedInfo sizeInfo)
{
base.OnRenderSizeChanged (sizeInfo);
SetButtonSizes ();
}
}

WPF 非常简单,看起来像这样:

<Window x:Class="Minesweeper.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="MainWindow"
Height="1000"
Width="1000">
<Grid Name="Grid" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>
</Window>

我已经试过了 Pixel Snapping ,这没有任何区别。

最佳答案

您应该在网格上将 UseLayoutRounding 设置为 true,而不是以编程方式调整按钮的大小。


但是,您可以使用 UniformGrid 大大简化代码

<Window ...>
<UniformGrid x:Name="grid"/>
</Window>

然后像这样添加按钮:

public MainWindow()
{
InitializeComponent();
SetSize(40, 40);
}

private void SetSize(int x, int y)
{
grid.Children.Clear();
grid.Columns = x;

for (int i = 0; i < x * y; i++)
{
grid.Children.Add(new Button
{
BorderThickness = new Thickness(1),
BorderBrush = Brushes.Gray,
Background = Brushes.DarkGray,
Foreground = Brushes.DarkGray,
Content = ""
});
}
}

关于c# - WPF网格白色条纹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50856185/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com