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

I linked my TextBox to a string value via

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

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

Thanks for any help!

Greetings

PS: One way is a custom ViewModel for the string. But I would rather do it somehow in XAML directly, if possible.

+6
c # wpf string-formatting
source share
3 answers

I think the only way to use ViewModel is to create your own ValueConverter.

So basically your choice:

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) { } } 
+7
source share

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

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

Greetings

+7
source share

Since the Age property is obviously the number here, another way would be to show Age as int and use the StringFormat Binding attribute:

 Text="{Binding Age, Mode=TwoWay, StringFormat='{}{0:#}'}" 
+4
source share

All Articles