Aaginor
Aaginor

Reputation: 4782

Silverlight: Changing a property of a static resource at runtime

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

I have a TextBox which displays a simple number. Then I have defined a style, which changes the Template of the TextBox 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-wired" in the TextBlock "txt1". So obviously, I can't change the number during runtime.

My question now is: What is the best way to change the displayed number? Creating a Style for each number looks a bit ineffective to me.

Thanks in advance, Frank

Upvotes: 2

Views: 2558

Answers (2)

Aaginor
Aaginor

Reputation: 4782

TemplateBinding to be able to set the value of the txt1-Text-Property 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>

Upvotes: 2

James Cadd
James Cadd

Reputation: 12216

The Style is just the look of the control, so in practice you'll need to re-use this style multiple times. A purist might say you shouldn't include data like the numbers (which must mean something in your application context) in a Style. So you could vary the number displayed when you use the style:

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

Even then, you might prefer to bind Text to your ViewModel (or whatever you use for data) and pull the number from there. Either one is Ok imo.

Upvotes: 0

Related Questions