我需要将数字显示为二进制字符串(例如8 => 1000)。当然我可以使用BitConverter转换它,并在代码隐藏文件中自己设置我的TextBox文本。但这看起来有些难看。是否可以将TextBox绑定到某个源并自动转换它?
答案 0 :(得分:4)
我建议使用ValueConverter
创建一个这样的类:
public class BinaryConverter : IValueConverter
{
public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return System.Convert.ToString(Convert.ToInt32(Convert.ToDouble(value)), 2);
}
public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return null;
}
}
然后你就可以像这样使用它(没有任何代码)
<Window.Resources>
<local:BinaryConverter x:Key="binConverter"></local:BinaryConverter>
</Window.Resources>
<StackPanel>
<Slider Name="sli" Minimum="0" Maximum="255" IsSnapToTickEnabled="True">
</Slider>
<TextBox Text="{Binding ElementName=sli,Path=Value,Mode=OneWay,Converter={StaticResource binConverter}}"></TextBox>
</StackPanel>