How can I have a Label change dynamically based on a Slider Value?

Posted by duney on Stack Overflow See other posts from Stack Overflow or by duney
Published on 2011-11-17T09:38:36Z Indexed on 2011/11/17 9:51 UTC
Read the original article Hit count: 127

Filed under:
|

I'm writing a grade calculator and I currently have a slider with a textbox beside it which displays the current value of the slider:

    <Slider Name="gradeSlider"
            Grid.Row="3"
            Grid.Column="2"
            VerticalAlignment="Center"
            Minimum="40"
            Maximum="100"
            IsSnapToTickEnabled="True"
            TickFrequency="5" 
            TickPlacement="BottomRight"/>
    <TextBox Name="targetGrade"
             Grid.Row="3"
             Grid.Column="3"
             Width="30"
             Height="23"
             Text="{Binding ElementName=gradeSlider, Path=Value}"
             TextAlignment="Center"/>

However I'm struggling to include a label which will show display a different grade classification based on the slider's value range. I'd have thought that I could create the label:

<Label     Name="gradeClass"
           Grid.Row="2"
           Grid.Column="2"
           HorizontalAlignment="Center"
           VerticalAlignment="Bottom"/>

And then use code:

        string gradeText;

        if (gradeSlider.Value >= 40 && gradeSlider.Value < 50)
        {
            gradeText = "Pass";
            gradeClass.Content = gradeText;
        }
        else if (gradeSlider.Value >= 50 && gradeSlider.Value < 60)
        {
            gradeText = "2:2";
            gradeClass.Content = gradeText;
        }
        else
        {
            gradeText = "so on...";
            gradeClass.Content = gradeText;
        }

But the label just stays as "Pass" whatever the slider value. Could somebody please advise me as to where I'm going wrong? I tried using Content = "{Binding Source = gradeText}" on the Label xaml and removing the gradeClass.Content's in the code but it complained that gradeText was declared but never used. Many thanks to anyone who can help.

© Stack Overflow or respective owner

Related posts about c#

Related posts about wpf