with value In WPF, you can associate the key in "{StaticResource key}" with a...">

Key binding in <object property = "{StaticResource key}" ... / "> with value

In WPF, you can associate the key in "{StaticResource key}" with a variable.

For instance. I have an ExecutionState variable with the states Active and Completed .

In my ResourceDictionary I have

<Style TargetType="{x:Type TextBlock}" x:Key="Active">
        <Setter Property="Foreground" Value="Yellow"/>
    </Style>
    <Style TargetType="{x:Type TextBlock}" x:Key="Completed">
        <Setter Property="Foreground" Value="Green"/>
    </Style>

Instead

<TextBlock Style="{StaticResource Active}"/>

I would like to have something like

<TextBlock Style="{StaticResource {Binding ExecutionState}}"/>

Thus, if the state changes the color of the text. Is something like this possible? I can achieve the desired functionality with triggers, but I have to reuse it in several places, and I don't want to clutter up my code. I also use MVVM.

thank

+3
source share
2 answers

, . DependencyProperty. StaticResource DependencyObject, DependencyProperty. Trigger .

0

. . .

<TextBlock  dep:CustomStyle.StyleName="{Binding ExecutionState}"    Text="Thiru"        />


public static  class CustomStyle
{
    static FrameworkPropertyMetadata _styleMetadata = new FrameworkPropertyMetadata(
                                     string.Empty, FrameworkPropertyMetadataOptions.AffectsRender, StyleNamePropertyChangeCallBack);

    public static readonly DependencyProperty StyleNameProperty =
        DependencyProperty.RegisterAttached("StyleName", typeof (String), typeof (CustomStyle), _styleMetadata);

    public static void SetStyleName(UIElement element, string value)
    {
        element.SetValue(StyleNameProperty, value);
    }
    public static Boolean GetStyleName(UIElement element)
    {
        return (Boolean)element.GetValue(StyleNameProperty);
    }


    public static void StyleNamePropertyChangeCallBack(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {

        FrameworkElement ctrl = d as FrameworkElement;

        if (ctrl.IsLoaded)
        {

            string styleName = Convert.ToString(e.NewValue);
            if (!string.IsNullOrEmpty(styleName))
            {
                ctrl.Style = ctrl.TryFindResource(styleName) as Style;
            }
        }
    }
}
0

All Articles