WPF入门3:UniformGrid布局

转载源小宅博客:http://www.bilibili996.com/Course?id=5079381000085

一.UniformGrid布局:

介绍了前面的Grid,接下来介绍的这个UniformGrid 就是Grid的简化版,每个单元格的大小相同,不需要定义行列集合。
每个单元格始终具有相同的大小,每个单元格只能容纳一个控件,将自动按照定义在其内部的元素个数,自动创建行列,并通常保持相同的行列数。
UniformGrid 中没有Row 和Column 附加属性,也没有空白单元格。

与Grid布局控件相比,UniformGrid布局控件很少使用。
Grid面板是用于创建简单乃至复杂窗口布局的通用工具。
UniformGrid面板是一个一种更特殊的布局容器,主要用于在一个刻板的网格中快速地布局元素。

1.基础案例:

效果图:
在这里插入图片描述

代码如下:

<Window x:Class="WPFDemo.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"
        xmlns:local="clr-namespace:WPFDemo"
        mc:Ignorable="d"
        Title="MainWindow" Height="300" Width="300">
    <Grid ShowGridLines="True" Margin="0,0,0,1">
        <UniformGrid Rows="2" Columns="2">
            <Button>第一个(0,0)</Button>
            <Button>第二个(0,1)</Button>
            <Button>第三个(1,0)</Button>
            <Button Name="btnAddBycode" Click="btnAddByCode_Click">第四个(1,1)</Button>
        </UniformGrid>
    </Grid>
</Window>

2.使用C#代码实现10个TextBlock控件布局:

实现效果,当点击“第四个(1,1)”按钮时,将界面变化为如下效果:
在这里插入图片描述

代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WPFDemo
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void btnAddByCode_Click(object sender, RoutedEventArgs e)
        {
            UniformGrid wp = new UniformGrid();
            //将wp添加为窗体的子控件
            this.Content = wp;
            wp.Margin = new Thickness(10,20,50,100);
            wp.Background = new SolidColorBrush(Colors.Orange);
            //遍历增加Rectangles
            TextBlock block;
            for (int i = 0; i <= 10; i++)
            {
                block = new TextBlock();
                block.Text = $"第{i}个";
                wp.Children.Add(block);
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值