1

I get an input from a different view model, and i need to show it in another window without the white spaces inserted. But it should not replace the original text. I need the white spaces removed only when displayed

Gethma
  • 299
  • 1
  • 5
  • 24
  • Are you databinding to the model property or are you setting it via `.Text = `? – JohanP Feb 05 '19 at 04:38
  • Consider using Value Converter. – kennyzx Feb 05 '19 at 04:40
  • @kennyzx the value converter will change the original text. It there any other way we can solve in the Xaml code level. Without converting? – Gethma Feb 05 '19 at 04:46
  • @Gethma Yes to which question? – JohanP Feb 05 '19 at 04:47
  • Are you databinding to the model property or are you setting it via .Text = ? Yes i do @johanP – Gethma Feb 05 '19 at 05:13
  • 1
    @Gethma if it is just for display, then one-way binding with a converter can do the trick. For example, if the property in the viewmodel is “Hello World”, you can bind to the property and display “HelloWorld” in the View with a value converter that removes the white spaces out of the original string. And since it’s one way binding you don’t have to worry that the View modifies the property in the ViewModel. – kennyzx Feb 05 '19 at 06:51

1 Answers1

1

Here you need Converter to trim your text like this:

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

And use converter with text binding in xaml like this:

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

<TextBox Text="{Binding YourTextWithSpaces, Converter={StaticResource noWhiteSpaceTextConverter}}" />
Ankush Madankar
  • 3,689
  • 4
  • 40
  • 74