【问题标题】:TextBlock StringFormat Trim ZerosTextBlock StringFormat 修剪零
【发布时间】:2018-02-12 11:57:51
【问题描述】:

我有一个 WPF 项目,其中包含一个 TextBlock 并绑定到一个数字 喜欢"0009012" 但我只想显示90120881012 如果必须显示881012

有没有办法使用 StringFormat 或者我必须编写一个转换器 为此?

这是我的代码:

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <TextBlock Text="{Binding Test}" StringFormat={}{????}/>
</Grid>
</Window>
using System.Windows;

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public string Test { get; set; }

        public MainWindow()
        {
            Test = "00090012";

            InitializeComponent();
            DataContext = this;
        }
    }
}

【问题讨论】:

  • "00090012" 不是数字。它是一个字符串。它按原样显示。
  • 您可以试试StringFormat={}{0:0}}" 看看显示的内容吗?
  • "StringFormat 有没有办法,还是我必须为此编写一个转换器?" 你必须编写一个转换器。

标签: c# wpf xaml binding string-formatting


【解决方案1】:

StringFormat 有什么办法吗,还是我必须为此写一个 Converter

后者。

没有可以在 XAML 中应用的 StringFormat 来删除数字中的所有前导零。另请注意,StringFormat 不适用于 string 值。

您可以编写一个转换器,例如在string 上调用TrimStart("0"),或者简单地从您绑定到的视图模型的源属性返回一个已经修剪过的值。

【讨论】:

    【解决方案2】:
    Test = Convert.ToInt32(Test).ToString();
    

    转换为整数将删除所有初始的0s,然后您可以使用ToString 方法将其转换回字符串。

    【讨论】:

    • 我必须在 WPF/XAML 中执行此操作,抱歉我没有说清楚。因为它是在运行时加载的 PrintLayout
    【解决方案3】:

    int integer = int.Parse(String.ToString()); 试试这个方法

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-16
      • 1970-01-01
      • 2012-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多