做一个滑块使用现有的IValueConverter [英] Make a slider use an existing IValueConverter
问题描述
我有一个滑块实施< A HREF =http://msdn.microsoft.com/en-us/library/system.windows.controls.slider%28v=vs.110%29.aspx相对=nofollow> System.Windows.Controls的。滑块:
class MySlider : Slider
{
public MySlider()
{
Minimum = 1;
Maximum = 1000;
}
}
我用这样的: MySlider滑块=新MySlider(){宽度= 400,名称=TheSlider};
它运作良好,但它是线性的。
我希望把它的非线性,因为合理的值是像1,2,10,1000(例如)。
所以我定义了一个非线性的<一个href="http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter%28v=vs.110%29.aspx"相对=nofollow>的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);
}
}
问:如何使滑盖使用的转换
推荐答案
更新:给你一个完整的工作code
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);
}
}
注意,现在,当你键入的东西在文本
它会改变根据您的公式滑块的价值。你可以把一个破发点上的转换
键,看看是否是你真正想要的滑盖
的值。
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
类,因为你只设置了最小
和最大
属性这已经是可用的实际对象本身。你只应延伸的控制,如果你在创建自定义的东西,如定义自己的依赖属性
。
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!