Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#/WPF Display Custom Strings (e.g. replace "0" with string.empty)

I've bound my TextBox to a string value via

 Text="{Binding AgeText, Mode=TwoWay}"  

How can I display string.empty or "" for the string "0", and all other strings with their original value?

Thanks for any help!

Cheers

PS: One way would be a custom ViewModel for the string.. but I'd prefer to do it somehow in the XAML directly, if it's possible.

like image 603
Joseph jun. Melettukunnel Avatar asked Jul 09 '09 09:07

Joseph jun. Melettukunnel


2 Answers

I think the only way beside using the ViewModel is creating a custom ValueConverter.

So basically your choices are:

ViewModel:

private string ageText;
public string AgeText{
    get{
        if(ageText.equals("0"))
            return string.empty;

        return ageText;
    }
    ...
}

ValueConverter:

public class AgeTextConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value.Equals("0"))
            return string.Empty;

        return value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {

    }
}
like image 191
chrischu Avatar answered Sep 21 '22 10:09

chrischu


I found something on http://www.codeproject.com/KB/books/0735616485.aspx
This will do the trick:

Text="{Binding AgeText, StringFormat='\{0:#0;(#0); }'}"

Cheers

like image 23
Joseph jun. Melettukunnel Avatar answered Sep 18 '22 10:09

Joseph jun. Melettukunnel