与Grid布局控件相比,UniformGrid布局控件很少使用。Grid面板是用于创建简单乃至复杂窗口布局的通用工具。UniformGrid面板是一个一种更特殊的布局容器,主要用于在一个刻板的网格中快速地布局元素。
下面用XAML代码实现一个示例,该示例使用4个按钮填充UniformGrid面板。:
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title第一个(0,0)第二个(0,1)第三个(1,0)第四个(1,1)
下面使用C#代码实现10个TextBlock的控件的布局。
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.Shapes; namespace WpfApp1 { WindowUniformGrid.xaml 的交互逻辑 WindowUniformGrid : Window { public WindowUniformGrid() { InitializeComponent(); } public void btnAddByCode_Click(object sender, RoutedEventArgs e) { UniformGrid wp = new UniformGrid(); .Content = wp; wp.Margin = new Thickness(0, 0, 0, 0); wp.Background = new SolidColorBrush(Colors.Red); //遍历增加Rectangles TextBlock block; for (int i = 0; i <= 10; i++) { block = new TextBlock(); block.Text = , i); wp.Children.Add(block); } } } }