StackPanels行

时间:2015-11-25 10:25:37

标签: c# wpf background row stackpanel

我正在创建一个包含100个人StackPanels的WPF应用程序,该应用程序已手动放置在特定位置,并为每个人分配一个起始背景颜色。 XAML部分如下所示:

<StackPanel Height="300" HorizontalAlignment="Left" Margin="228,120,0,0" Name="stackPanel1"
   VerticalAlignment="Top" Width="6" Background="Red" />
<StackPanel Background="Red" Height="300" HorizontalAlignment="Left" Margin="234,120,0,0" 
   Name="stackPanel2" VerticalAlignment="Top" Width="6" />
<StackPanel Background="Red" Height="300" HorizontalAlignment="Left" Margin="240,120,0,0" 
   Name="stackPanel3" VerticalAlignment="Top" Width="6" />
<StackPanel Background="Red" Height="300" HorizontalAlignment="Left" Margin="246,120,0,0" 
   Name="stackPanel4" VerticalAlignment="Top" Width="6" />
<StackPanel Background="Red" Height="300" HorizontalAlignment="Left" Margin="252,120,0,0" 
   Name="stackPanel5" VerticalAlignment="Top" Width="6" />

可以看出,Background对于前5个是Red,而Width6(每个Margin一个接一个地放置6个单位,使它们连接起来。)

现在,我想要的是,例如,.cs能够通过创建包含它们的行来处理它们(或多或少像[stackPanel1stackPanel2,..., stackPanel100])。我想这样做,例如,使用以下代码更改前5个颜色:

for(int i=0;i<100;i++){
    if(i<10){
        stackPanelsRow[i].Background = Colors.Blue; //Change the background color to blue
    }
    if(i>10 && i<20){
        stackPanelsRow[i].Background = Colors.Green; //Change the background color to green
    }
    //...
}

如果它们是在Designer中创建的单个实体并根据上述条件手动放置,我如何构造StackPanels这一行?

enter image description here

2 个答案:

答案 0 :(得分:1)

在WPF中,您可以使用User来实现此目的:

create()

如果您不想为同一类型的所有元素指定相同的颜色,可以使用x:样式的键,然后应用于您想要的每个StackPanel:

Style

然后:

<Window.Resources>
    <Style TargetType="StackPanel">
        <Setter Property="Background" Value="Red"></Setter>
    </Style>
</Window.Resources>
<Grid>
    <StackPanel ... /> <!--You don't need to set background here anymore-->
    <StackPanel ... />
    ....
</Grid>

<小时/> 修改:执行此操作的另一个选项是:

<Style TargetType="StackPanel" x:Key="MyStyle">

然后在代码隐藏中:

<StackPanel Style="{StaticResource MyStyle}" ... />

答案 1 :(得分:0)

通过StackPanel包裹您的堆栈面板

<StackPanel x:Name="StackPanelTest" Orientation="Horizontal">
    <StackPanel/>
    <StackPanel/>
    <StackPanel/>
</StackPanel>

您可以访问

var someStackPanel = StackPanelTest.Children[0] as StackPanel;