将数字显示为来自绑定源的二进制

Ker*_*nic 5 binary binding ivalueconverter

我需要将数字显示为二进制字符串(例如8 => 1000).当然我可以使用BitConverter转换它,并在代码隐藏文件中自己设置我的TextBox文本.但这看起来有些难看.是否可以将TextBox绑定到某个源并自动转换它?

Mar*_*kus 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你就可以像这样使用它(后面没有任何代码)

<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>
Run Code Online (Sandbox Code Playgroud)