Daniel Gruszczyk
Daniel Gruszczyk

Reputation: 5612

Problems with WP8 Slider

My XAML:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition/>
        <ColumnDefinition Width="auto"/>
    </Grid.ColumnDefinitions>
    <Slider Name="sldLength" Margin="0 0 0 0"  Grid.Column="0" 
            Minimum="5" Maximum="30" SmallChange="1"  LargeChange="1"
            Value="10" ValueChanged="sldLength_ValueChanged"/>
    <TextBlock Name="tblLength" Margin="0 10 5 0" Text="10" Grid.Column="1"
            FontSize="{StaticResource PhoneFontSizeMediumLarge}"/>
</Grid>

My Code begind:

private void sldLength_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
    tblLength.Text = e.NewValue.ToString();
}

2 problems:

  1. ValueChanged event fires when the application is loaded, this is not a problem, but for some reason at the time of the event firing tblLength is NULL and this throws an exception, I have wrapped it in an if statement checking for that NULL, but this surely should not be the issue right?
  2. Slider does not change in the increments of 1, even though SmallChange and LargeChange are set to 1. How could that be fixed?

Thnks for any help...

--EDIT--

Solved problem 1 with Chepene suggestion.
Solved problem 2 with little cheeky event handler:

private void sldLength_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
    ((Slider)sender).Value = Math.Round(((Slider)sender).Value);
}

Upvotes: 0

Views: 1625

Answers (2)

Nomi Khan
Nomi Khan

Reputation: 31

This worked perfectly for me. First check the Slider's OldValue, either it null or not.

private void slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
   if(slider.OldValue != null)
   {
      textbox1.Text = silder1.Value.ToString();
   }
}

hope this help.

Upvotes: 0

Chepene
Chepene

Reputation: 1128

You can use Bindings. Smth like this:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition/>
        <ColumnDefinition Width="auto"/>
    </Grid.ColumnDefinitions>
    <Slider Name="sldLength" Margin="0 0 0 0"  Grid.Column="0" 
            Minimum="5" Maximum="30" SmallChange="1"  LargeChange="1"
            Value="10"/>
    <TextBlock Name="tblLength" Margin="0 10 5 0" Text="{Binding ElemantName=sldLength, Path=Value}" Grid.Column="1"
               FontSize="{StaticResource PhoneFontSizeMediumLarge}"/>
</Grid>

Here tblLength takes its text from the value of sldLength.

Upvotes: 1

Related Questions