Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Showing numbers as binary from a bound source

I need to display a number as binary string (e.g. 8 => 1000). Sure I can convert it using BitConverter and set the text of my TextBox on my own in the code behind file. But this looks somewhat ugly. Is it possible to bind the TextBox to some source and convert it automatically?

like image 755
KernelPanic Avatar asked Oct 11 '22 10:10

KernelPanic


1 Answers

I would suggest to use a ValueConverter

Create a class like this:

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;
    }
}

Then you can use it like this (without any code behind)

<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>
like image 65
Markus Avatar answered Nov 03 '22 21:11

Markus