cbutler
cbutler

Reputation: 943

C# WPF - Change column background color in code

I've never really worked with WPF before so this might be a newb question but is there a way to change the background color of a column of a WPF grid?

I want to change column 0's background color from the code.

  <Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition x:Name="Banner" Width="25" />
        <ColumnDefinition Width="Auto" />
    </Grid.ColumnDefinitions>

    <Border Grid.Row="0" Grid.Column="0" Background="Gainsboro" />
    <Border Grid.Row="1" Grid.Column="0" Background="Gainsboro" />
    <Border Grid.Row="2" Grid.Column="0" Background="Gainsboro" />
    <Border Grid.Row="3" Grid.Column="0" Background="Gainsboro" />

    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
        <RowDefinition Height="*" />
        <RowDefinition Height="*" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <Label x:Name="titleLabel" 
           Grid.Row="1" Grid.Column="1" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="3" 
           FontWeight="Bold"
           Content="Title" >

    </Label>
    <Label x:Name="msgLabel" 
           Grid.Row="2" Grid.Column="1" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="3" 
           Content="Title" >
    </Label>
</Grid>

Upvotes: 3

Views: 3644

Answers (1)

Evk
Evk

Reputation: 101613

You can add one more border and place it in first column (note RowSpan):

<Border x:Name="firstColumn" 
        Grid.Column="0" 
        Grid.Row="0" 
        Grid.RowSpan="4" 
        Background="Transparent"/>

When need to change background from code, just do

firstColumn.Background = Brushes.Red;

Upvotes: 3

Related Questions