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循環(huán)動態(tài)添加Label,我要怎么獲取每個Label的名稱呢,我想給添加出來的Label加上背景。
2 回答

至尊寶的傳說
TA貢獻1789條經(jīng)驗 獲得超10個贊
方法1,在創(chuàng)建的時候把Label保存在一個List中
方法2,遍歷canEAChip_Idle5內(nèi)的控件,然后判斷是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; } } } //調(diào)用如下(將所有Control禁掉): LayoutRoot.GetVisuals().OfType <Control>().ToList().ForEach(item => { item.IsEnabled = false; });
- 2 回答
- 0 關注
- 1192 瀏覽
添加回答
舉報
0/150
提交
取消