Silverlight: Changing a Static Resource Property at Runtime

changing a static resource during runtine is something that sounds not possible.

I have a TextBox that displays a prime number. Then I defined a style that changes the TextBox template to become a round TextBox:

<Style x:Key="RoundNumberDisplay" TargetType="TextBox">
        <Setter Property="Width" Value="22"/>
        <Setter Property="Height" Value="22"/>

        <Setter Property="Template">
            <Setter.Value>

                    <ControlTemplate>
                        <Border x:Name="brd1" Width="20" Height="20" CornerRadius="15">
                            <TextBlock x:Name="txt1" Foreground="#222" TextAlignment="center" Text="1" FontSize="14" FontWeight="ExtraBold" VerticalAlignment="center" />
                            <Border.Background>
                                <RadialGradientBrush GradientOrigin=".3, .3">
                                    <GradientStop Color="{StaticResource ColorBackground1}" Offset=".15"/>
                                    <GradientStop Color="{StaticResource ColorForeground1}" Offset="1"/>
                                </RadialGradientBrush>
                            </Border.Background>
                        </Border>
                    </ControlTemplate>

            </Setter.Value>
        </Setter>

    </Style>

      

As you can see, the displayed text is "hard" in the "txt1" text box. So obviously I cannot change the number at runtime.

Now my question is, what is the best way to change the displayed number? Styling each number looks a little ineffective to me.

Thanks in advance, Frank

+2


source to share


2 answers


TemplateBinding to be able to set the txt1-Text-Property value from the target TextBox. Important: the target type for the ControlTemplate must be set!



    <Style ...

                    <ControlTemplate **TargetType="TextBox"**>
                            ...

                            <TextBlock x:Name="txt1" Foreground="#222" TextAlignment="center" **Text="{TemplateBinding Text}"** FontSize="14" FontWeight="ExtraBold" VerticalAlignment="center" />
                    </ControlTemplate>
    </Style>

      

+2


source


A style is simply the look and feel of a control, so in practice you will have to reuse that style multiple times. A purist might say that you shouldn't include numbers like data (which should mean something in the context of your application) in style. This way you can change the number displayed when using the style:

<TextBox Style={StaticResource RoundNumberDisplay} x:Name="TextBoxOne" Text="1"/>

      



Even then, you can bind the Text to your ViewModel (or whatever you are using for the data) and pull the number from there. Any of them are Ok imo.

0


source







All Articles