我需要将数字显示为二进制字符串(例如8 => 1000)。当然,我可以使用BitConverter对其进行转换,并在文件背后的代码中自行设置TextBox的文本。但这看起来有些丑陋。是否可以将TextBox绑定(bind)到某些源并自动将其转换?

最佳答案

我建议使用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>

关于binary - 将数字显示为来自绑定(bind)源的二进制,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5468018/

10-11 10:48
查看更多