I had a query with regards to Win UI sliders and their labels. From what I have seen so far, labels tend to be integers denoting the value of the slider. Is it possible to use custom labels, for example strings instead? Is this possible through the usage of label templates? I've scoured the Documentation and other articles, but have not found anything that is too helpful. Is it possible to get an example of how this can be coded?
I have a slider that ranges from the values 10 to 30, but I want the labels to be after every ten ticks. The labels could be something like "Slow" (at value 10), "Medium" (at value 20) and "Fast" (at value 30) for example. Could I do this by reading from an array in the code-behind, or in the XAML part itself?
Many thanks for your time, in advance!
I tried looking at the documentation and looking at other articles online outlining custom labels, but they don't show anything with regards to custom string labels, rather only integers and/or floats. Hence, I'm not too sure if this is possible.
You can create a custom Slider
that takes a value converter:
SliderEx.cs
public class SliderEx : Slider
{
public IValueConverter? ValueConverter { get; set; }
protected override void OnApplyTemplate()
{
base.OnApplyTemplate();
this.LayoutUpdated += Slider_LayoutUpdated;
}
private void Slider_LayoutUpdated(object? sender, object e)
{
if (VisualTreeHelper
.GetOpenPopupsForXamlRoot(this.XamlRoot)
.FirstOrDefault() is not Popup popup ||
popup.Child.FindDescendant<TextBlock>() is not TextBlock popupTextBlock)
{
return;
}
popupTextBlock.SetBinding(
TextBlock.TextProperty,
new Binding
{
Source = this,
Path = new PropertyPath(nameof(this.Value)),
Mode = BindingMode.OneWay,
Converter = this.ValueConverter,
});
this.LayoutUpdated -= Slider_LayoutUpdated;
}
}
ValueToSpeedConverter.cs
public class ValueToSpeedConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
return (double)value switch
{
>= 0 and < 20 => "Slow",
>= 20 and < 30 => "Medium",
>= 30 => "Fast",
_ => $"{value}?",
};
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
And use it like this:
<StackPanel>
<StackPanel.Resources>
<local:ValueToSpeedConverter x:Key="ValueToSpeedConverter" />
</StackPanel.Resources>
<local:SliderEx
x:Name="SliderControl"
ValueConverter="{StaticResource ValueToSpeedConverter}"/>
</StackPanel>