【问题标题】:Overlapping button cells in WPF gridWPF网格中重叠的按钮单元格
【发布时间】:2021-12-30 22:49:22
【问题描述】:

我想实现按钮的二次网格,例如没有网格单元重叠。

同样重要的是,按钮应位于每个单元格的中心,并且彼此之间有明显的间隙。

<Grid  Margin="0,0,0,-6" 
      RenderTransformOrigin="0.505,0.323" 
      HorizontalAlignment="Right" 
      Width="810" Height="610" 
      VerticalAlignment="Bottom">

这是我一直在使用的代码 sn-p (MainWindow.xaml.cs):

for (int i = 0; i < gridSize; i++)
{
    RowDefinition r = new RowDefin
    r.Height = new GridLength(1000, GridUnitType.Star);
    grid.RowDefinitions.Add(r);
                
    for (int j = 0; j < gridSize; j++)
    {
                    ColumnDefinition c = new ColumnDefinition();
                    c.Width = new GridLength(20, GridUnitType.Star);
                    grid.ColumnDefinitions.Add(c);

                    Button b = new Button();
                    b.Width = 20;
                    b.Height = 20;
                    
                    b.Background = Brushes.Transparent;
                    Grid.SetRow(b, i);
                    Grid.SetColumn(b, j);
                    grid.Children.Add(b);

    }
}

不幸的是,这会产生看似重叠的配置。所以我的问题是我应该如何解决重叠问题并在各个按钮之间构建空间。

【问题讨论】:

  • 您是否有理由不在 XAML 中执行此操作?
  • 你不应该使用绝对值,使用相对值作为宽度和高度
  • 我想在MVVM的上下文中动态实现按钮网格设置。

标签: c# wpf xaml


【解决方案1】:

您需要做的是更加熟悉 WPF 标准控件。我相信您所寻求的是UniformGridTextBlock 的某种组合。

<UniformGrid  Height="100" Width="120">
    <UniformGrid.Resources>
        <Style x:Name="BorderStyle" TargetType="Border">
            <Setter Property="Height" Value="40"/>
            <Setter Property="Width" Value="40"/>
            <Setter Property="BorderBrush" Value="Red"/>
            <Setter Property="BorderThickness" Value="2"/>
            <Setter Property="Background" Value="Brown"/>
        </Style>
        <Style x:Name="TextBlockStyle" TargetType="TextBlock">
            <Setter Property="HorizontalAlignment" Value="Center"/>
            <Setter Property="VerticalAlignment" Value="Bottom"/>
            <Setter Property="Foreground" Value="Wheat"/>

        </Style>                
    </UniformGrid.Resources>
    <Border>
        <TextBlock Text="Pizza"/></Border>
    <Border>
        <TextBlock Text="Pizza"/>
    </Border>
    <Border >
        <TextBlock Text="Pizza"/>
    </Border>
    <Border>
        <TextBlock Text="Pizza"/>
    </Border>
</UniformGrid>

这为您提供了一个基本的网格模式,由您决定是否满足您的需要:

项目的 MVVM 仅用于存储数据。然后可以将该数据插入到控件中以动态创建项目。

【讨论】:

    猜你喜欢
    • 2011-06-09
    • 1970-01-01
    • 2019-02-15
    • 1970-01-01
    • 1970-01-01
    • 2021-02-22
    • 1970-01-01
    • 1970-01-01
    • 2013-09-26
    相关资源
    最近更新 更多