Problems with WP8 Slider

最后都变了- 提交于 2019-12-24 20:28:30

问题


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);
}

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/17076134/problems-with-wp8-slider

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!