我的WPF窗口中有如下所示的工具栏,请帮助我在后面的代码中动态更改标签的前景色。谢谢…
<DockPanel Height="60" VerticalAlignment="Top">
<ToolBar Name="MyToolBar" DockPanel.Dock="Top" Height="60" VerticalAlignment="Top" FlowDirection="RightToLeft"
FontFamily="Calibri" FontSize="16" FontWeight="Bold" Background="#FFEEF5FD" Foreground="Black" ScrollViewer.VerticalScrollBarVisibility="Disabled">
<Button Name="BtnSubmit" Style="{DynamicResource TStyle}" Click="BtnSubmit_Click" Tag="New" Height="52" Width="60"
IsDefault="True" Margin="0,0,0,1">
<StackPanel Margin="0" Height="54"
<Image Source="/Img/Save 04.png" Height="25" Margin="16,0"/>
<Label Content="Save" Margin="0,0,0,0" HorizontalContentAlignment="Center" VerticalContentAlignment="Center"
HorizontalAlignment="Center" VerticalAlignment="Center"/>
</StackPanel>
</Button>
<Button Name="BtnApply" Style="{DynamicResource TStyle}" Click="BtnApply_Click" Tag="New" Height="52"
IsDefault="True" Margin="0,1,0,2" Width="85">
<StackPanel Margin="0" Height="52" Width="82">
<Image Source="/Img/ApplyIcon.png" Height="25" Margin="29,0,26,0"/>
<Label Content="Edit" Margin="-15,0,-23,0" HorizontalContentAlignment="Center" VerticalContentAlignment="Center"
HorizontalAlignment="Center" VerticalAlignment="Center"/>
</StackPanel>
</Button>
</ToolBar>
</DockPanel>
要更改所有TextBlock
元素的Foreground
,必须定义Brush
资源并使用{DynamicResource}
将其分配给所有相关的TextBlock
元素:
MainWindow.xaml
<Window>
<Window.Resources>
<SolidColorBrush x:Key="ButtonLabelForegroundBrush" Color="Black" />
</Window.Resources>
<DockPanel>
<ToolBar>
<Button>
<TextBlock Foreground="{DynamicResource ButtonLabelForegroundBrush}" />
</Button>
</ToolBar>
</DockPanel>
</Window>
MainWindow.xaml.cs
private void ChangeTextBlockForeground()
{
var brush = FindResource("ButtonLabelForegroundBrush") as SolidColorBrush;
brush.Color = Colors.Red;
}