C#のWPFでConverterを使ってスライダーの倍率表示文字列を変換する

C# コンピュータ
C#

スライダーの値をラベルに倍率として表示させたい。その際0.1~10.0の範囲が選択できるようにしたい。

ファイル名:ScaleConverter.cs

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


namespace ScaleConverter01;

public class ScaleConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        double x = (double)value / 10.0d;
        return string.Format(" {0:0.0}倍", x);
    }
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

ファイル名:MainWindow.xaml

<Window x:Class="ScaleConverter01.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:ScaleConverter01"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.Resources>
        <local:ScaleConverter x:Key="ScaleConverter"/>
    </Window.Resources>
    <Grid>
        <StackPanel
            Orientation="Horizontal">
            <Slider
                x:Name="Slider1"
                Width="120"
                Minimum="1"
                Maximum="100"
                SmallChange="1"
                LargeChange="2"
                Value="10" />
            <Label
                Content="{Binding ElementName=Slider1,Path=Value, Converter={StaticResource ScaleConverter}}"/>
        </StackPanel>
    </Grid>
</Window>

スライダーが少数しか扱えないと思い、スライダーでは0~100の範囲を設定しConverterで10で割って小数点以下を表示していますが、小数点以下も扱えるようなので必要ない処理だったようです。

コメント