I’m trying to display the value of a slider control in a TextBlock. However I keep getting a NullRerferenceException when I try to load the dialog.
public partial class GeneralSettingsDialog : Window
{
public GeneralSettingsDialog()
{
InitializeComponent();
}
private void DistSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
DistTextBlock.Text = DistSlider.Value.ToString();
}
}
XAML:
<TabItem Header="Miscellaneous" Name="tabItem1" Background="#FFF0F0F0">
<Grid Height="230" Background="#FFF0F0F0">
<TextBlock Height="23" HorizontalAlignment="Left" Margin="13,13,0,0" Name="textBlock1" Text="Spacing" VerticalAlignment="Top" />
<Slider Height="23" HorizontalAlignment="Left" IsSnapToTickEnabled="True" TickPlacement="BottomRight" Margin="13,35,0,0" Name="DistSlider" VerticalAlignment="Top" Width="100" Interval="1" Maximum="50" Minimum="1" ValueChanged="DistSlider_ValueChanged" />
<TextBlock Height="23" HorizontalAlignment="Left" Margin="111,35,0,0" Name="DistTextBlock" Text="TextBlock" VerticalAlignment="Top" />
</Grid>
</TabItem>
Not exactly sure why your way isn’t working, I guess the controls are not fully initialized when the first value changed event is thrown. But you can do it that way directly in xaml without any code behind:
in TextBlock bind directly to the slider’s current value and remove the value changed event handler:
PS:
When you attach to the slider’s value changed event in codebehind after InitializeComponent() your approach should also work fine: