做项目的时候遇见了这个问题,在网上查找了一些资料之后解决了这个问题,我把我的代码贴出来分享一下。
先说我的要求:主窗口上有五个TextBlock控件和两个Button按钮(Get和Set),单击Get按钮之后弹出一个对话框,显示出所有TextBlock控件的Name值;单击Set按钮之后,将所有的TextBlock的背景色设为红色。
这是主窗体的代码(控件是手动拖的,所有属性值有点乱):
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="ExplodeProgram.MainWindow" x:Name="Window" Title="MainWindow" Width="600" Height="400" xmlns:my="clr-namespace:ExplodeProgram"> <Grid x:Name="LayoutRoot"> <TextBlock Name="hello" Margin="78,77,98,196" TextWrapping="Wrap" Foreground="#FFFB240F" FontSize="64"> <Run Language="zh-cn" Text="Hello World!"/></TextBlock> <TextBlock Height="23" HorizontalAlignment="Left" Margin="30,179,0,0" Name="textBlock1" Text="TextBlock1" VerticalAlignment="Top" Width="100" /> <TextBlock Height="23" HorizontalAlignment="Left" Margin="136,179,0,0" Name="textBlock2" Text="TextBlock2" VerticalAlignment="Top" Width="100" /> <TextBlock Height="23" HorizontalAlignment="Left" Margin="291,179,0,0" Name="textBlock3" Text="TextBlock3" VerticalAlignment="Top" Width="100" /> <TextBlock Height="23" HorizontalAlignment="Left" Margin="420,179,0,0" Name="textBlock4" Text="TextBlock4" VerticalAlignment="Top" Width="100" /> <Button x:Name="get" Content="Get" Margin="102,0,411,45" VerticalAlignment="Bottom" Height="25" Width="65" Click="get_Click" /> <Button x:Name="set" Content="Set" Width="65" Height="25" Click="set_Click" Margin="185,291,328,45" /> </Grid> </Window>
这是后台单击事件的代码:
private void set_Click(object sender, RoutedEventArgs e) { foreach (UIElement element in LayoutRoot.Children) { if (element is TextBlock) { TextBlock current = ((TextBlock)element); //设置背景 current.Background = Brushes.Red; } } } private void get_Click(object sender, RoutedEventArgs e) { string str = ""; foreach (UIElement element in LayoutRoot.Children) { if (element is TextBlock) { TextBlock current = ((TextBlock)element); str += current.Name + "\r\n"; } } //显示Name值 MessageBox.Show(str); }
搞定。