【问题标题】:WPF change dynamicresource in codebehindWPF 在代码隐藏中更改动态资源
【发布时间】:2012-05-30 21:04:48
【问题描述】:

标准的 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>

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

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

问候,

米歇尔

【问题讨论】:

    标签: wpf radio-button controltemplate


    【解决方案1】:

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

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

    您也可以通过

    访问资源
    Resources["mykey"]
    

    【讨论】:

    • 我用不同的颜色更新了 Application.Current.Resources("ControlLightColor"),没有任何反应。我还在绑定元素上做了一个 RaisePropertyChanged,也不起作用。
    • 也许你必须调用 InitializeComponent();创建两种样式并切换样式可能会更好。或者将 gradientstop 颜色绑定到一个属性(MVVM)
    • 对,嗯,那么我唯一能想到的就是创造新的风格。顺便说一句,你想要完成什么?也许在 xaml 中更容易做到
    • 我有一个带有显示多个单选按钮的项目控件的堆栈面板。单选按钮有一种颜色,表示必须选择其中一个。单击单选按钮时,所有单选按钮必须更改为不同的颜色,以指示已回答强制性问题。如果不做一些模板工作,就不可能给单选按钮一个颜色。我在考虑 controltemplate 触发器,但所有 rb 都必须获得新颜色,而不仅仅是单击的那个。
    • 嗯,这看起来很有希望:绑定到椭圆
    【解决方案2】:

    解决办法:

    <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 的思考点赞。

    【讨论】:

      猜你喜欢
      • 2010-10-20
      • 2011-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多