Darth Coder
Darth Coder

Reputation: 1798

How to change the properties of a UI control within a grid once the row and column is known

I am having trouble accessing a UI control (in my case: labels and Rectangles) arranged within a grid. I need to access this control at a specific location in the grid (given the row and column no.) and need to change its background color, font-size etc.

The code I am using so far looks like this:

foreach (UIElement ui in myGrid.Children)
{
     int rowIndex = System.Windows.Controls.Grid.GetRow(ui);
     int colIndex = System.Windows.Controls.Grid.GetColumn(ui);
     if (rowIndex == TargetRow && colIndex == TargetCol)
           //change the background property of the ui control to yellow
}

The If statement is where I am stumped (assuming the remainder code is correct too). How do I use the properties of this UIELement 'ui'. Please help!

Upvotes: 0

Views: 219

Answers (2)

McGarnagle
McGarnagle

Reputation: 102763

You'll have to cast the element to the appropriate type. You might want to try casting to the lowest element in the class hierarchy that contains the property you're looking for -- for Background, this would be Control:

if (rowIndex == TargetRow && colIndex == TargetCol)
{ 
    //change the background property of the ui control to yellow
    if (ui is Control)
        ((Control)ui).Background = Brushes.Yellow;
}

You could also use a Linq-style iterator:

foreach (var control in myGrid.Children.OfType<Control>()
    .Where(child => Grid.GetRow(child) == TargetRow && Grid.GetColumn(child) == TargetCol)
{
    control.Background = Brushes.Yellow;
}

Upvotes: 1

Clemens
Clemens

Reputation: 128061

You would either set Control.Background for the Labels or Shape.Fill for the Rectangles:

if (rowIndex == TargetRow && colIndex == TargetCol)
{
    if (ui is Control)
    {
        ((Control)ui).Background = Brushes.Yellow;
    }
    else if (ui is Shape)
    {
        ((Shape)ui).Fill = Brushes.Yellow;
    }
}

Instead of explicitly looping over all child elements, you may use LINQ to find the matching UIElement like this:

using System.Linq;
...

var ui = myGrid.Children.Cast<UIElement>().FirstOrDefault(
    c => Grid.GetColumn(c) == TargetCol && Grid.GetRow(c) == TargetRow);

if (ui is Control)
...

Upvotes: 1

Related Questions