Home > Net >  Assigning color to dynamic number of shapes in WPF
Assigning color to dynamic number of shapes in WPF

Time:11-18

I have this C# code that I wrote to test a few things out. All it does right now is assigning colors to rectangles on the screen:

var tmp = FillSquare();
A.Fill = (Brush)tmp;
B.Fill = (Brush)tmp;
C.Fill = (Brush)tmp;
D.Fill = (Brush)tmp;
E.Fill = (Brush)tmp;
F.Fill = (Brush)tmp;

This works.

I there a way to write this more elegantly, like a foreach loop, for example, which assigns the color to each rectangle?

I'm not sure if it matters, but I placed the rectangles on a canvas, and not a grid.

CodePudding user response:

Yes, you can do this more elegantly with a foreach loop like you suggest. By iterating through each Rectangle on your canvas using OfType<Rectangle>():

var tmp = FillSquare();
foreach (Rectangle rect in LogicalTreeHelper.GetChildren(yourCanvasName).OfType<Rectangle>())
{
     rect.Fill = (Brush)tmp;
}

CodePudding user response:

Well, if you really want the elegant way in WPF - I think you should stick to MVVM pattern and declare a property in the ViewModel:

private Brush _myBrush;
public Brush MyBrush
{
    get => _myBrush;
    set
    {
        if (value != _myBrush)
        {
            _myBrush = value;
            PropertyChanged?.Invoke(this, nameof(MyBrush));
        }
    }
}

And then just bind your shapes colors to this property in XAML:

<Shape Fill="{Binding MyBrush}"/>

Once the value of MyBrush is changed - the shapes fill color will update automatically.

You also might want to place them into a separate WPF control to have additional logic isolated.

  • Related