问题
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:
- 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?
- 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