for (int i = 0; i < counter; i++){ Label lb = new Label(); lb.Width = 50; lb.Height = 35; lb.FontFamily = new FontFamily("LiSu"); lb.HorizontalAlignment = HorizontalAlignment.Left; lb.VerticalAlignment = VerticalAlignment.Bottom; lb.FontWeight = FontWeights.Bold; Canvas.SetTop(lb, i * (-2)); lb.Background = Brushes.Transparent; lb.HorizontalContentAlignment = HorizontalAlignment.Center; lb.VerticalContentAlignment = VerticalAlignment.Center; canEAChip_Idle5.Children.Add(lb);}我用for循环动态添加Label,我要怎么获取每个Label的名称呢,我想给添加出来的Label加上背景。
2 回答
至尊宝的传说
TA贡献1789条经验 获得超10个赞
方法1,在创建的时候把Label保存在一个List中
方法2,遍历canEAChip_Idle5内的控件,然后判断是Label的话就加上背景
foreach (UIElement element in canEAChip_Idle5.Children) { if (element is Label) { Label current = ((Label)element); //设置背景 current.Background = Brushes.Transparent; } }
方法3,如果使用VisualTreeHelper的话,参考如下:
//定义扩展方法 public static IEnumerable <DependencyObject> GetVisuals(this DependencyObject root) { int count = VisualTreeHelper.GetChildrenCount(root); for (int i = 0; i < count; i++) { var child = VisualTreeHelper.GetChild(root, i); yield return child; foreach (var descendants in child.GetVisuals()) { yield return descendants; } } } //调用如下(将所有Control禁掉): LayoutRoot.GetVisuals().OfType <Control>().ToList().ForEach(item => { item.IsEnabled = false; });
- 2 回答
- 0 关注
- 1160 浏览
添加回答
举报
0/150
提交
取消