How to set the back ground color of grid-column in wpf?
Asked Answered
S

5

10

I have a wpf mvvm application. And have a GRID with multiple columns

whats best way to set the back ground color of grid-column in wpf?

Sine answered 14/6, 2011 at 16:56 Comment(0)
W
7

One way:

Create a rectangle and set its fill to the color of your choice.
Then set its Grid.RowSpan value to a large number or the number of rows you have.

Winfield answered 14/6, 2011 at 17:5 Comment(3)
will it be transparent ? I mean i have some values in that column.Sine
Yes, all content that you place in your Grid Cells should be rendered in front of your Rectangle. You can also adjust the transparency of your Rectangle in the Visual Studio properties editor and change the A value in the RGBA selection section.Winfield
OR simply you could add a new grid in each of the columns and use their background propertyPirozzo
H
23

dabble125's answer was perfect but to give you a sample and to mention a note that it is important where to place your rectangle see the code:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition/>
        <ColumnDefinition/>
        <ColumnDefinition/>
    </Grid.ColumnDefinitions>

    <!--  this is not a good place for text block.
          the text block is beneath the rectangle  
          so it would not be seen  -->
    <!--<TextBlock Grid.Column="1"  Text="Some Text"/>-->

    <Rectangle Grid.Column="1" Grid.RowSpan="1000">
        <Rectangle.Fill>
            <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                <GradientStop Color="#FF83FF97" Offset="0" />
                <GradientStop Color="White" Offset="1" />
            </LinearGradientBrush>
        </Rectangle.Fill>
    </Rectangle>

    <TextBlock Grid.Column="1"  Text="Some Text"/>
</Grid>
Humerus answered 14/6, 2011 at 17:29 Comment(0)
W
7

One way:

Create a rectangle and set its fill to the color of your choice.
Then set its Grid.RowSpan value to a large number or the number of rows you have.

Winfield answered 14/6, 2011 at 17:5 Comment(3)
will it be transparent ? I mean i have some values in that column.Sine
Yes, all content that you place in your Grid Cells should be rendered in front of your Rectangle. You can also adjust the transparency of your Rectangle in the Visual Studio properties editor and change the A value in the RGBA selection section.Winfield
OR simply you could add a new grid in each of the columns and use their background propertyPirozzo
C
3

Create a rectangle and set its fill to the color of your choice.

Only having :

<Rectangle
Grid.Column="1"
Fill="#e8ebf1" />

works for me.

The Grid.RowSpan of previous answers is actually useless, and the LinearGradientBrush demonstrated is over-complicated for what is asked.

Compendious answered 12/4, 2021 at 9:8 Comment(2)
I do not see how this answers the question at the top of this page, but it should. Please edit according to How to Answer or delete the answer. Otherwise it risks being flagged as "not an answer" and being deleted.Subterranean
Short and efficient, I like it.Hypercorrect
M
0

Instead of hardcoding the RowSpan value to a fixed number you can set the value using data binding to its parent grid RowDefinitions.Count property

<Rectangle
   Grid.Column="1" 
   Grid.RowSpan="{Binding RelativeSource={RelativeSource AncestorType=Grid}, 
   Path=RowDefinitions.Count }"
   Fill="DeepSkyBlue" />

Example showing how ZIndex can affect the visibility of control :

<Window x:Class="LayoutPanels.GridColumnBackgroundColor"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Setting Grid column background color" Height="200" Width="500">

    <Grid Background="Pink" ShowGridLines="True">
        <Grid.RowDefinitions>
            <RowDefinition></RowDefinition>
            <RowDefinition ></RowDefinition>
            <RowDefinition></RowDefinition>
        </Grid.RowDefinitions>

        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition />
            <ColumnDefinition />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>

        <Rectangle
              Grid.Column="0" Grid.RowSpan="{Binding RelativeSource={RelativeSource AncestorType=Grid}, Path=RowDefinitions.Count }"
              Fill="DeepSkyBlue" />
        <TextBlock Grid.Column="0" Grid.Row="0" >Row1Column1</TextBlock>
        <TextBlock Grid.Column="0" Grid.Row="1" >Row2Column1</TextBlock>
        <TextBlock Grid.Column="0" Grid.Row="2" >Row3Column1</TextBlock>

        <!--This TextBlock is not visible as we have added green Rectangle on top of it!-->
        <TextBlock Grid.Column="1" Grid.Row="0" TextWrapping="Wrap">I am not visible as I am behind green rectangle</TextBlock>
        <Rectangle
            Grid.Column="1" Grid.RowSpan="{Binding RelativeSource={RelativeSource AncestorType=Grid}, Path=RowDefinitions.Count }"
            Fill="LawnGreen" />

        <TextBlock Grid.Column="1" Grid.Row="1" >Row2Column1</TextBlock>
        <TextBlock Grid.Column="1" Grid.Row="2" >Row3Column1</TextBlock>


        <!--This TextBlock is now visible as we have increased the value of its z index !-->
        <TextBlock Grid.Column="2" Grid.Row="0" TextWrapping="Wrap" Panel.ZIndex="1" Margin="5">I am visible and now in front of rectangle</TextBlock>
        <Rectangle
            Grid.Column="2" Grid.RowSpan="{Binding RelativeSource={RelativeSource AncestorType=Grid}, Path=RowDefinitions.Count }"
            Fill="Yellow" />

        <TextBlock Grid.Column="2" Grid.Row="1" >Row2Column1</TextBlock>
        <TextBlock Grid.Column="2" Grid.Row="2" >Row3Column1</TextBlock>
    </Grid>
</Window>

Output:

enter image description here

Miracidium answered 1/3 at 12:0 Comment(0)
M
0

You can also create a custom grid control whose ColumnDefinition property accepts column colour in XAML.

enter image description here

and shows grid with those color column like

enter image description here

MainWindow XAML code:

<Window x:Class="GridWithColoredColumn.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:GridWithColoredColumn"
        Title="MainWindow" SizeToContent="WidthAndHeight">
    <StackPanel>
        <local:CustomGrid x:Name="CustomGrid1" Height="150" Width="400">
            <Grid.ColumnDefinitions>
                <ColumnDefinition local:CustomGrid.ColumnColor="GreenYellow"/>
                <ColumnDefinition local:CustomGrid.ColumnColor="DeepSkyBlue"/>
                <ColumnDefinition local:CustomGrid.ColumnColor="Yellow"/>
                <ColumnDefinition />
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition/>
                <RowDefinition/>
            </Grid.RowDefinitions>
            <TextBlock  Grid.Row="0" Grid.Column="0">Row0Column0</TextBlock>
            <TextBlock  Grid.Row="1" Grid.Column="0">Row1Column0</TextBlock>
        </local:CustomGrid>
        <Button Click="ButtonClickHandler">Change Color</Button>
    </StackPanel>
    <x:Code>
        <![CDATA[            
        private void ButtonClickHandler(object sender, RoutedEventArgs e)
        {
           CustomGrid1.ColumnDefinitions[1].SetValue(CustomGrid.ColumnColorProperty,Brushes.Red);
        }
      ]]>
    </x:Code>
</Window>

CustomGrid code:

using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Shapes;

namespace GridWithColoredColumn
{
    public class CustomGrid : Grid
    {
        private bool _doingInit;
        // Attached property definition inside the custom Grid
        public static readonly DependencyProperty ColumnColorProperty =
            DependencyProperty.RegisterAttached("ColumnColor", typeof(Brush), typeof(CustomGrid), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender, OnColumnColorChanged));

        public static Brush GetColumnColor(DependencyObject obj)
        {
            return (Brush)obj.GetValue(ColumnColorProperty);
        }

        public static void SetColumnColor(DependencyObject obj, Brush value)
        {
            obj.SetValue(ColumnColorProperty, value);
        }

        // Callback method for property change
        private static void OnColumnColorChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {

            ColumnDefinition? col = d as ColumnDefinition;
            if (col != null)
            {
                CustomGrid? grid = col.Parent as CustomGrid;
                if (grid != null && !grid._doingInit)
                {
                    // Implement logic to set column color based on the attached property
                    int columnIndex = grid.ColumnDefinitions.IndexOf(col);
                    
                    Rectangle? rect = grid.FindName($"{grid.Name}_R{columnIndex}") as Rectangle;
                    if (grid.ColumnDefinitions.Count > 0)
                    {
                        rect.Fill = (Brush)e.NewValue;
                    }
                }
            }
        }

        public override void BeginInit()
        {
            _doingInit = true;
            base.BeginInit();
        }
        public override void EndInit()
        {
            AddRectangle();
            _doingInit = false;
            base.EndInit();
        }

        private void AddRectangle()
        {
            string gridName = this.Name?? Guid.NewGuid().ToString("N");
            int i = 0;
            foreach (var col in this.ColumnDefinitions)
            {
                if (col.GetValue(CustomGrid.ColumnColorProperty) is Brush colColor)
                {
                    Rectangle rect = new Rectangle();
                    rect.Name = $"{gridName}_R{i}";
                    RegisterName(rect.Name, rect);
                    rect.SetValue(Panel.ZIndexProperty, -1);
                    rect.Fill = (Brush)col.GetValue(CustomGrid.ColumnColorProperty); 
                    rect.SetValue(Grid.ColumnProperty, i++);
                    rect.SetValue(Grid.RowProperty, 0);
                    rect.SetValue(Grid.RowSpanProperty, this.RowDefinitions.Count);
                    this.Children.Add(rect);
                }
            }
        }
    }
}
Miracidium answered 3/3 at 15:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.