首页 > 解决方案 > 有没有办法在代码隐藏中设置容器的第 n 个孩子的样式?

问题描述

有没有办法用代码设置容器的第 n 个孩子的样式?

<StackPanel x:Name="container">
   <TextBlock x:Name="1st"/>
   <TextBlock x:Name="2nd"/>
   <TextBlock x:Name="3rd"/>
</StackPanel>

我想要这样的东西:

container.children[2].Style = this.FindResource("style") as Style;

标签: c#.netwpf

解决方案


您必须将孩子强制转换为FrameworkElementfirst 的衍生物,它声明了Style财产。对于您的代码示例,您可以将孩子强制转换为TextBlock.

var textBlock = (TextBlock)container.Children[2];
textBlock.Style = this.FindResource("style") as Style;

FrameworkElement如果有其他类型,更通用的解决方案是将孩子强制转换为。

var frameworkElement = (FrameworkElement)container.Children[2];
frameworkElement.Style = this.FindResource("style") as Style;

如果您的面板不像您的示例中那样静态,您也应该检查 的边界Children,以及孩子是否真的是类型 FrameworkElement(如果可能有其他元素不是从它派生的)。

if (container.Children.Count >= 2 && container.Children[2] is FrameworkElement frameworkElement)
   frameworkElement.Style = this.FindResource("style") as Style;

推荐阅读