【问题标题】:How to display a text without the whitespaces in Xaml textbox如何在 Xaml 文本框中显示没有空格的文本
【发布时间】:2019-02-05 04:34:53
【问题描述】:

我从不同的视图模型获得输入,我需要在另一个窗口中显示它,而不插入空格。但它不应取代原文。我只需要在显示时删除空格

【问题讨论】:

  • 您是数据绑定到模型属性还是通过.Text = 设置它?
  • 考虑使用值转换器。
  • @kennyzx 值转换器将更改原始文本。我们可以在 Xaml 代码级别解决任何其他问题。不转换?
  • @Gethma 是哪个问题?
  • @Gethma 如果它只是为了显示,那么与转换器的单向绑定可以解决问题。例如,如果视图模型中的属性是“Hello World”,您可以绑定到该属性并使用值转换器在视图中显示“HelloWorld”,该值转换器会从原始字符串中删除空格。而且由于它是一种方式绑定,因此您不必担心 View 会修改 ViewModel 中的属性。

标签: c# wpf xaml


【解决方案1】:

这里你需要Converter 来修剪你的文本:

using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Media;

[ValueConversion( typeof( string ), typeof( string ) )]
public class NoWhiteSpaceTextConverter : IValueConverter
{
    public object Convert( object value, Type targetType, object parameter, CultureInfo culture )
    {
        if ( ( value is string ) == false )
        {
            throw new ArgumentNullException( "value should be string type" );
        }

        string returnValue = ( value as string );

        return returnValue != null ? returnValue.Trim() : returnValue;
    }

    public object ConvertBack( object value, Type targetType, object parameter, CultureInfo culture )
    {
        throw new NotImplementedException();
    }
}

并在xaml 中使用带有文本绑定的转换器,如下所示:

<Windows.Resources>         
     <converter:NoWhiteSpaceTextConverter x:Key="noWhiteSpaceTextConverter"></converter:NoWhiteSpaceTextConverter>            
</Windows.Resources>

<TextBox Text="{Binding YourTextWithSpaces, Converter={StaticResource noWhiteSpaceTextConverter}}" />

【讨论】:

  • [ValueConversion( typeof( string ), typeof( string ) )] 这行是什么意思?
  • 更好地理解转换器是可选但很好的做法:请参阅此答案stackoverflow.com/a/9628979/2106315
猜你喜欢
  • 1970-01-01
  • 2017-02-10
  • 1970-01-01
  • 1970-01-01
  • 2011-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多