问题描述
我有一个 滑块 实现 System.Windows.Controls.滑块:
class MySlider : Slider
{
public MySlider()
{
Minimum = 1;
Maximum = 1000;
}
}
我这样使用它:MySlider slider = new MySlider() { Width = 400, Name = "TheSlider"};
效果很好,但它是线性的.
我想让它非线性,因为合理的值就像 1、2、10、1000(例如).
所以我定义了一个非线性 IValueConverter 像这样:
It works well, but it is linear.
I want to make it non-linear because sensible values are like 1, 2, 10, 1000 (for instance).
So I defined a non-linear IValueConverter like this:
public class LogScaleConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return (int)Math.Log((int)value);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return (int)Math.Exp((double)value);
}
}
问题:如何让滑块使用这个转换器?
推荐答案
更新:给你一个完整的工作代码.
MainWindow.xaml
<StackPanel>
<StackPanel.Resources>
<spikes:LogScaleConverter x:Key="LogScaleConverter"/>
</StackPanel.Resources>
<TextBox x:Name="InputNumberTextBox" Width="100" Text="{Binding InputNumber, Mode=TwoWay}"/>
<Slider Width="1000"
Minimum="1"
Maximum="100"
Value="{Binding ElementName=InputNumberTextBox,Path=Text, Mode=TwoWay,Converter={StaticResource LogScaleConverter}}"/>
</StackPanel>
LogScaleConverter.cs
public class LogScaleConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var stringValue = value.ToString();
if (string.IsNullOrWhiteSpace(stringValue)) return null;
var intValue = int.Parse(stringValue);
return Math.Log(intValue);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return (int)Math.Exp((double)value);
}
}
现在请注意,当您在 文本框
中输入内容时,它会根据您的公式更改滑块的值.您可以在 Convert
上放置一个断点,看看这是否是您在 slider
中真正想要的值.
Notice now that when you type something in the textbox
it'll change the value of the slider based on your formula. You can put a break point on the Convert
and see if that is the value that you really want in the slider
.
我认为没有必要创建 MySlider
类,因为您只设置了 Minimum
和 Maximum
属性可用于实际对象本身.只有在创建自定义内容(例如定义自己的 Dependency Properties
)时,才应该扩展控件.
I don't think it is necessary to create a MySlider
class since you are only setting the Minimum
and Maximum
properties which is already available on the actual object itself. You should only be extending a control if you are creating custom stuff like defining your own Dependency Properties
.
这篇关于使滑块使用现有的 IValueConverter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!