C#更改特定行的背景颜色

11
我已经从Grid App(XAML)模板(C# Windows Store)创建了一个新项目。 到目前为止,我还没有更改模板中的任何内容,但我想要更改网格中特定行的背景颜色。
<!--
    This grid acts as a root panel for the page that defines two rows:
    * Row 0 contains the back button and page title
    * Row 1 contains the rest of the page layout
-->
<Grid Style="{StaticResource LayoutRootStyle}">
    <Grid.RowDefinitions>
        <RowDefinition Height="140"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>

我想要改变第0行(其中包含页面标题)的背景颜色。有什么建议吗?谢谢!

这一行包括:

    <!-- Back button and page title -->
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Button x:Name="backButton" Click="GoBack" IsEnabled="{Binding Frame.CanGoBack, ElementName=pageRoot}" Style="{StaticResource BackButtonStyle}"/>
        <TextBlock x:Name="pageTitle" Text="{StaticResource AppName}" Grid.Column="1" IsHitTestVisible="false" Style="{StaticResource PageHeaderTextStyle}"/>
    </Grid>
2个回答

17

你不能直接在Grid.Row上设置背景颜色,相反,应该在占据该行的元素上设置Background属性。

例如:

<Grid Style="{StaticResource LayoutRootStyle}">
  <Grid.RowDefinitions>
    <RowDefinition Height="140"/>
    <RowDefinition Height="*"/>
  </Grid.RowDefinitions>
  <Grid Background="Red" Grid.Row="0">
    <TextBlock>Test</TextBlock>
  </Grid>
</Grid>

编辑: 更新了Silverlight部分;TextBlock没有背景,所以您必须将控件放置在另一个具有背景的Border或Grid容器中。代码已更新以反映此更改。


很遗憾,文本块项目不包含背景属性。我已经编辑了我的帖子以显示该行中有哪些项目。 - user1951083
但我不想改变只有按钮的背景,它必须是整个行。 - user1951083
1
我已经相应地更新了我的答案,你必须将你的控件包装在一个Border或Grid中(这些都有Background属性)。 - Dutts
只是想知道是否可以在StandardStyles.xaml文件中完成,这样我就不必编辑每个页面了。在我的所有页面中,我都调用StaticResource LayoutRootStyle。<Style x:Key="LayoutRootStyle" TargetType="Panel"> <Setter Property="Background" Value="#FFDDF2AE" /> <Setter Property="ChildrenTransitions"> <Setter.Value> <TransitionCollection> <EntranceThemeTransition/> </TransitionCollection> </Setter.Value> </Setter> </Style> 我已经为整个主体设置了背景属性。 - user1951083
我不是完全确定,如果你创建一个样式并将TargetType设置为“Grid”,会发生什么? - Dutts
显示剩余2条评论

2
在你需要的地方插入边框怎么样?
<Grid Style="{StaticResource LayoutRootStyle}">
  <Grid.RowDefinitions>
    <RowDefinition Height="140"/>
    <RowDefinition Height="*"/>
  </Grid.RowDefinitions>
    <Border Background="Red" Grid.ColumnSpan="1"></Border>
    <TextBlock>Test</TextBlock>
    <Border Background="blue" Grid.Row="1" Grid.ColumnSpan="1"></Border>
    <TextBlock Grid.Row="1">Test2</TextBlock>
 </Grid>

请注意,如果要包含更多的列,您可以指定列跨度。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接