首页 > 解决方案 > 如何更改 XAML 样式文件中的颜色

问题描述

我有一个已定义样式的 ProgressBar,我需要在运行时更改他的颜色(在样式中定义)。

我一直在尝试寻找一个小时,但没有什么能解决我的问题

这是我的风格(ProgressBar.xaml),我需要更改它们的值LPercentBackground1ColorLPercentBackground2Color使用位置

    <SolidColorBrush x:Key="LPercentBackground1Color" Color="Red" />
    <SolidColorBrush x:Key="LPercentBackground2Color" Color="White" />

    <Style x:Key="NormalStyle" TargetType="{x:Type ProgressBar}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type ProgressBar}">
                    <Grid>
                        <VisualStateManager.VisualStateGroups>
                            <VisualStateGroup x:Name="CommonStates">
                                <VisualState x:Name="Determinate" />
                                <VisualState x:Name="Indeterminate" />
                            </VisualStateGroup>
                        </VisualStateManager.VisualStateGroups>
                        <Border x:Name="PART_Track" Margin="0" BorderThickness="0" CornerRadius="7" />
                        <Border x:Name="PART_Indicator" Margin="0" BorderThickness="0" CornerRadius="5" HorizontalAlignment="Left"
                                    Background="{StaticResource LPercentBackground1Color}" ClipToBounds="True">
                            <Border x:Name="DiagonalDecorator" Width="5000">
                                <Border.Background>
                                    <DrawingBrush TileMode="Tile" Stretch="None" Viewbox="0,0,1,1" Viewport="0,0,36,34" ViewportUnits="Absolute">
                                        <DrawingBrush.RelativeTransform>
                                            <TranslateTransform X="0" Y="0" />
                                        </DrawingBrush.RelativeTransform>
                                        <DrawingBrush.Drawing>
                                            <GeometryDrawing Brush="{StaticResource LPercentBackground2Color}" Geometry="M0,0 -18,0 -36,34 -18,34 Z" />
                                        </DrawingBrush.Drawing>
                                    </DrawingBrush>
                                </Border.Background>
                            </Border>
                        </Border>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

我找不到如何改变这些,所以我需要你的帮助。谢谢 !

标签: c#wpfxamldynamic

解决方案


如果您DynamicResource在模板中使用标记扩展:

Background="{DynamicResource LPercentBackground1Color}"

Brush...您可以在ResourceDictionary运行时替换:

Resources["LPercentBackground1Color"] = Brushes.Green;

推荐阅读