views:

542

answers:

3

Hello,

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.

+4  A: 

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)
    {

    }
}
chrischu
I'd go with the custom ValueConverter
Julien Poulin
Thanks a lot! ValueConverter is just what I was looking for.Cheers
Joseph Melettukunnel
Me too :) Its cleaner ;)
Arcturus
I remember using # or something like that in Excel, to display empty Cells if the value is 0. Wouldn't that also work in StringFormat?
Joseph Melettukunnel
+1  A: 

Since the Age property is obviously a number here, an other way to go would be to expose the Age as an int and use the StringFormat attribute of the Binding:

Text="{Binding Age, Mode=TwoWay, StringFormat='{}{0:#}'}"
Julien Poulin
You were faster :) I can here see the problem that if a user enters the Value string.empty, my other classes would need a "0" for that or they will crash, so I guess the best way to go is the ValueConverter. Cheers
Joseph Melettukunnel
+1  A: 

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

Joseph Melettukunnel