Working with the Uniform Grid in WPF


In this article I will introduce the Uniform Grid object. The uniform grid object arranges content in its area so that all the cells in the grid have the same dimension. It represents a perfect solution if someone prefers to prevent the headache of ordering controls within an ordinary Grid object.

First, the Uniform grid belongs to the System.Windows.Controls. Primitives.  It could be found in the tool box at the bottom.

 

Figure1

Let's make a small gadget with the uniform grid, to do so follow those steps

1.      Copy and paste the bellow code in the XAML code zone

 

<Window x:Class="myWpfApplication.Window1"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    Title="Window1" Height="300" Width="300" Loaded="Window_Loaded">

   

        <UniformGrid Margin="15,15,15,15" Name="uniformGrid1">

            <Label Name="lbl1" MouseDown="lbl1_MouseDown"></Label>

            <Label Name="lbl2" MouseDown="lbl2_MouseDown"></Label>

            <Label Name="lbl3" MouseDown="lbl2_MouseDown"></Label>

            <Label Name="lbl4" MouseDown="lbl1_MouseDown"></Label>

        </UniformGrid>

   

</Window>

 

2.      Now, switch to the code behind zone by right clicking on the window and clicking the view code context menu item.

3.      Copy and paste this below code

 

private void Window_Loaded(object sender, RoutedEventArgs e)

        {

            lbl1.Background = System.Windows.Media.Brushes.Aqua;

            lbl4.Background = System.Windows.Media.Brushes.Aqua;

        }

 

        private void lbl1_MouseDown(object sender, MouseButtonEventArgs e)

        {

            lbl1.Background = System.Windows.Media.Brushes.Aqua;

            lbl2.Background = System.Windows.Media.Brushes.White;

            lbl3.Background = System.Windows.Media.Brushes.White;

            lbl4.Background = System.Windows.Media.Brushes.Aqua;

        }

 

        private void lbl2_MouseDown(object sender, MouseButtonEventArgs e)

        {

            lbl1.Background = System.Windows.Media.Brushes.White;

            lbl2.Background = System.Windows.Media.Brushes.Aqua;

            lbl3.Background = System.Windows.Media.Brushes.Aqua;

            lbl4.Background = System.Windows.Media.Brushes.White;

        }

 

4.      Now, fire up the application and try to click each of the labels in the uniform grid and observe

 

 

Figure1

 

The uniform grid is a perfect control for how wants to avoid wasting time, in configuring a classic grid as it automatically resizes all the controls to have uniform size and dimension. That's it.

Good Dotneting!!!