WPF slider and dates

I want the slider to select dates. For example, every hour in the last two days. Also, the slider must have a legend below with values. How can i do this?

I made a slider with a data context as DoubleCollection from the total number of hours per day and changed the tooltip using my own ValueConverter. But when I change the value, a tooltip shows the real values ​​- the total number of hours per day. Also I have no idea how to add a legend.

+3
source share
1 answer

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 TextBlockslider to the value.

A is ValueConverterused to convert the value 0-48 to 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();
        }
    }

}
+3
source

Source: https://habr.com/ru/post/1765935/


All Articles