c# - 有没有办法在代码隐藏中设置容器的第 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;
解决方案
您必须将孩子强制转换为FrameworkElement
first 的衍生物,它声明了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;
推荐阅读
- node.js - 如何在 Sequelize 中更新两个关系表
- r - 用NA替换某些变量,一个变量是NA
- react-native - expo-apple-authentication:“TypeError:null 不是对象(评估'NativeUnimoduleProxy.viewManagersNames')”
- java - 为什么我的 GetMapping 注释没有被识别
- postgresql - 错误:postgresql 中“%”处或附近的语法错误
- react-native - 如何在组件以反应原生方式安装时为视图设置动画?
- ios - 构建时在 xcode 中出错 - PhaseScriptExecution 失败,退出代码为非零
- r - GRU(门控循环单元)出现错误,导致生成器函数的数据用完,并且没有为 R(RStudio)中的“每个键输入..”提供数据
- mysql - 显示每种类型的电影数量
- ruby-on-rails - 错误:找不到有效的 gem 'rails' (>= 0),原因如下:在 docker 容器内