C# 如何在Xaml文本框中显示没有空格的文本

C# 如何在Xaml文本框中显示没有空格的文本,c#,wpf,xaml,C#,Wpf,Xaml,我从一个不同的视图模型中获得一个输入,我需要在另一个没有插入空格的窗口中显示它。但它不应取代原文。我只需要在显示时删除空白此处您需要按如下方式修剪文本: using System; using System.Globalization; using System.Windows.Data; using System.Windows.Media; [ValueConversion( typeof( string ), typeof( string ) )] public class NoWhit

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

此处您需要按如下方式修剪文本:

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();
    }
}
<Windows.Resources>         
     <converter:NoWhiteSpaceTextConverter x:Key="noWhiteSpaceTextConverter"></converter:NoWhiteSpaceTextConverter>            
</Windows.Resources>

<TextBox Text="{Binding YourTextWithSpaces, Converter={StaticResource noWhiteSpaceTextConverter}}" />
并在
xaml
中使用具有文本绑定的转换器,如下所示:

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();
    }
}
<Windows.Resources>         
     <converter:NoWhiteSpaceTextConverter x:Key="noWhiteSpaceTextConverter"></converter:NoWhiteSpaceTextConverter>            
</Windows.Resources>

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


<代码>您是否将数据绑定到Model属性,或者是通过<代码> > Text=< /代码>来设置它?考虑使用值转换器。@ KNYZX值转换器将更改原始文本。在Xaml代码级别,我们没有其他方法可以解决这个问题。不转换?@Gethma Yes到哪个问题?@Gethma如果它只是为了显示,那么使用转换器的单向绑定就可以实现。例如,如果viewmodel中的属性为“Hello World”,则可以绑定到该属性,并使用值转换器在视图中显示“HelloWorld”,该值转换器将删除原始字符串中的空白。由于它是单向绑定,您不必担心视图会修改ViewModel中的属性。[ValueConversion(typeof(string),typeof(string))]这一行的意思是什么?更好地理解转换器是可选的,但也是一个很好的实践:请参见此答案