Slider, WPF. A Slider has a minimum and a maximum. It has a button that a user can drag back and forth. We use the ValueChanged event handler to determine how a slider is being used.
Add Slider. Please begin by creating a WPF project and dragging a Slider to the window. We use the ValueChanged attribute in the XAML.
Event handler info. In the XAML, type "ValueChanged" and press tab—a new event handler in C# code will be created. In the event handler, we can access the Slider object from the sender.
Info An alternative is to use the RoutedPropertyChangedEventArgs (this is not shown). In the code, we access Value to get a double.
Detail This returns a double variable. It can be any value between Minimum (default 0) and Maximum (default 10).
Tip Try setting the Minimum and Maximum properties in your XAML code. These properties can also be set in a C# event handler.
Example code. When we use the Slider in this program, the Window Title is changed to read "Value: 3.9/10" or something similar. It updates instantly as the Slider is used.
using System.Windows;
using System.Windows.Controls;
namespace WpfApplication13
{
/// <summary>/// Interaction logic for MainWindow.xaml/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Slider_ValueChanged(object sender,
RoutedPropertyChangedEventArgs<double> e)
{
// ... Get Slider reference.
var slider = sender as Slider;
// ... Get Value.
double value = slider.Value;
// ... Set Window Title.
this.Title = "Value: " + value.ToString("0.0") + "/" + slider.Maximum;
}
}
}
Discussion. A Slider is by default horizontal. But in WPF programs, we can rotate the slider in any direction. Use the corner boxes on the control in the Visual Studio designer.
Also Often the Minimum and Maximum attributes need to be adjusted. This can be done in the XAML, or a Slider_Loaded event handler.
Summary. This basic example used the Slider control. It used C# code in the Slider_ValueChanged event handler to dynamically apply changes the user interface, as sliding occurred.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jun 28, 2021 (rewrite).