WPF在后面的代码中更改动态资源

时间:2012-05-24 09:33:59

标签: wpf radio-button controltemplate

标准RadioButton不支持设置椭圆的颜色。所以,我从这个位置拿了一个radiobutton模板作为自定义RadioButton的基础: RadioButton Styles and Templates

<Ellipse.Fill>
<LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
    <LinearGradientBrush.GradientStops>
        <GradientStopCollection>
            <GradientStop Color="{DynamicResource ControlLightColor}" />
            <GradientStop Color="{DynamicResource ControlMediumColor}" Offset="1.0" />
        </GradientStopCollection>
    </LinearGradientBrush.GradientStops>
</LinearGradientBrush>

ControlLightColor和ControlMediumColor定义为:

<Color x:Key="ControlLightColor">#ffff9a</Color>
<Color x:Key="ControlMediumColor">#ffff9a</Color>

这给了我们一个黄色椭圆。

如何在代码隐藏中更改此颜色?

此致

米歇尔

2 个答案:

答案 0 :(得分:0)

按照以下方式创建样式: Creating a Style in code behind

然后将其分配给您的element.Style

您还可以通过

访问资源
Resources["mykey"]

答案 1 :(得分:0)

解决方案:

<Ellipse x:Name="Border" StrokeThickness="1" Fill="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=DataContext.RadioButtonColor}">

        Public ReadOnly Property RadioButtonColor() As SolidColorBrush
        Get
            Dim solidColorBrush As SolidColorBrush

            If MyBusinessLogic Then
                solidColorBrush = _radioButtonNotRequiredBrush
            Else
                solidColorBrush = _radioButtonRequiredBrush
            End If

            Return solidColorBrush
        End Get
    End Property

赞赏JRB的思考。