简体   繁体   English

在网格内填充矩形

[英]Fill a Rectangle inside a Grid

I have created a Grid in WPF with rectangles inside, and the XAML is the following one: 我已经在WPF中创建了一个带有内部矩形的Grid,而XAML如下所示:

<Grid HorizontalAlignment="Left" Name="grid1" VerticalAlignment="Top" Initialized="grid1_Initialized">
    <Rectangle Height="300" HorizontalAlignment="Left" Margin="228,120,0,0" Name="stackPanel1" VerticalAlignment="Top" Width="40" Fill="Red" />
    <Rectangle Fill="OrangeRed" Height="300" HorizontalAlignment="Left" Margin="268,120,0,0" Name="stackPanel2" VerticalAlignment="Top" Width="40" />
    <Rectangle Fill="Orange" Height="300" HorizontalAlignment="Left" Margin="308,120,0,0" Name="stackPanel3" VerticalAlignment="Top" Width="40" />
    ...
</Grid>

(Just ignore the names stackPanel1, stackPanel2, ..., they're now rectangles). (只需忽略名称stackPanel1,stackPanel2,...,它们现在是矩形)。

What I want to do is to assign a Fill color, but I can't get access to them. 我想做的是分配一种填充颜色,但是我无法访问它们。 What I have tried is: 我试过的是:

foreach (var stackpanl in mainGrid.Children.OfType<StackPanel>())
{
     int row = Grid.GetRow(rectangle);

     if (Grid.GetRow(stackpanl) < 2)
     {
          stackpanl.Background = new SolidColorBrush(Colors.Blue);                    
     }
}

But this returns a value of 0 for row at each iteration. 但这在每次迭代中返回的行值为0。

I have also tried: 我也尝试过:

for(int i = 0; i < 15 ; i++)
        {
            var rectangle = grid1.Children[i];
            int row = Grid.GetRow(rectangle);
            if (row == 2)
            {
                rectangle.Fill = new SolidColorBrush(Colors.Magenta);
            }
        }

But apparently Fill is not a property regarding a grid1.Children[i] element. 但是显然Fill不是关于grid1.Children [i]元素的属性。

How can I change the color of the individual rectangles? 如何更改各个矩形的颜色? Thanks! 谢谢!

Fill is a property of Rectangle. 填充是矩形的属性。 You have already given names to Rectangles. 您已经为Rectangles命名了。 Cast the returned child to Rectangle. 将返回的孩子转换为Rectangle。

eg; 例如;

Rectangle r = new Rectangle();
r.Fill = new SolidColorBrush(Colors.BlanchedAlmond);

// //

Rectangle rectangle = (Rectangle)grid1.Children[i];
rectangle.Fill = new SolidColorBrush(Colors.Magenta);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM