简体   繁体   中英

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.

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

    }
}

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

由于Age属性在这里显然是一个数字,另一种方法是将Age公开为int并使用BindingStringFormat属性:

Text="{Binding Age, Mode=TwoWay, StringFormat='{}{0:#}'}"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM