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

发布于 2024-10-27 04:48:46 字数 126 浏览 6 评论 0原文

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

单调的奢华 2024-11-03 04:48:46

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

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>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文