Y.Yanavichus
Y.Yanavichus

Reputation: 2417

WPF Slider and dates

I want to make a slider to select dates. For example, every hour in last two days. Also slider should has a legend on the bottom with values. How could I do it?

I made slider with DataContext as DoubleCollection from total hours in date and changed tooltip using a custom ValueConverter. But when I change value, tooltip shows real values - total hours in date. Also I have no idea how to add a legend.

Upvotes: 3

Views: 5144

Answers (1)

Mart
Mart

Reputation: 5788

Here is a working example. First we create a slider from 0 to 48 rounded to integer values (TickFrequency="1" IsSnapToTickEnabled="True") then add a TextBlock bound to the slider value.

A ValueConverter is used to convert the 0-48 value into a date.

<Window x:Class="StackOverflow2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:StackOverflow2"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <local:HourToDateConverter x:Key="MyHourConverter"/>
    </Window.Resources>
    <StackPanel>
        <Slider x:Name="MySlider" Minimum="0" Maximum="48" TickFrequency="1" IsSnapToTickEnabled="True"/>
        <TextBlock Text="{Binding ElementName=MySlider, Path=Value, Converter={StaticResource MyHourConverter}}" HorizontalAlignment="Center"/>
    </StackPanel>
</Window>

And the code behind:

using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;

namespace StackOverflow2
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }
    public class HourToDateConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            object result = DependencyProperty.UnsetValue;
            if (value is double)
                result = DateTime.Now.Date.AddHours((double)value);
            return result;
        }
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

}

Upvotes: 3

Related Questions