5
I’m doing some initial tests with the WPF and I came up with this question.
Make no mistake:
<DockPanel Margin="5">
<TextBox x:Name="myTextBox" DockPanel.Dock="Right" Width="50" />
<Slider x:Name="mySlider" Width="300" SmallChange="1" TickPlacement="BottomRight" IsSnapToTickEnabled="True" ValueChanged="mySlider_ValueChanged" Minimum="1" />
</DockPanel>
private void mySlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
myTextBox.Text = (Convert.ToInt32(mySlider.Value)).ToString();
}
On the other hand, changing the order of the controls get:
An Exception of type 'System.Nullreferenceexception' occurred in mySlider_error.exe but was not handled in user code
Makes a mistake:
<DockPanel Margin="5">
<Slider x:Name="mySlider" Width="300" SmallChange="1" TickPlacement="BottomRight" IsSnapToTickEnabled="True" ValueChanged="mySlider_ValueChanged" Minimum="1" />
<TextBox x:Name="myTextBox" DockPanel.Dock="Right" Width="50" />
</DockPanel>
I know I can easily solve this scenario using, for example:
<TextBox x:Name="myTextBox" DockPanel.Dock="Right" Width="50" Text="{Binding ElementName=mySlider,Path=Value}" />
I only wish to know why the exception is made?
Post the code of:
mySlider_ValueChanged
– rubStackOverflow
My colleague @rubStackOverflow is absolutely right: post the code! My supposition is that this code, being an event handler, is executed at least once when the object
mySlider
is created. If that code has/references to the objectmyTextBox
, the order of creation certainly matters.– Luiz Vieira
Yes refers to myTextbox.
– gtpt
what’s on your mySlider_ValueChanged?
– Marco Souza
private void mySlider_ValueChanged(Object Sender, Routedpropertychangedeventargs<double> e) { myTextBox.Text = (Convert.Toint32(mySlider.Value). Tostring(); }
– gtpt
Have you seen what you’re going through
(Convert.ToInt32(mySlider.Value)).ToString();
so that you convert to int and then to string?– Marco Souza
Do not have to convert to string to save in Text?
– gtpt