Search code examples
c#wpfslider

Selecting a start value for a Slider without triggering ValueChanged Event


I want to set the slider Value to 10 and then make it possible to move it down or up again, but when I set a Value for the slider, I get an Error which says

System.NullReferenceException

this is the code:

        <MenuItem Header = "Edit">
            <MenuItem Header="Transparence">
                <Slider Width="100" Name="transparence" ValueChanged="transparenz_ValueChanged" 
                        IsMoveToPointEnabled="True" Value="10"/>
            </MenuItem>
        </MenuItem>

this is the method where the exception occures

    private void transparenz_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
    {
        Input.Opacity = transparenz.Value * 0.1;
    }

when I remove the value from the XAML File, everything works fine

I just want to have this Slider start at the end

The Slider


Solution

  • If you want something to happen before having its event handlers attached, you need to set it in your constructor in code behind instead of XAML, like this:

    In your MainWindow.xaml.cs (or whatever your view is named .xaml.cs):

    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window {
        public MainWindow() {
            InitializeComponent();
            transparenz.Value = 10;
        }
        ... Rest of your code here
    }
    

    Then remove Value="10" from your XAML file.