How to set the font case of a listbox item in WPF?

2019-08-05 08:01发布

I have a ListBox in a WPF Window. Based on the selected item of a ComboBox, the ListBox items are retrieved from database and bound as the ListBox's ItemSource. I want to change the case of the ListBox items, i.e., when i bind all the items are in uppercase. I want to change the case to capitalize only the starting letter of a word.

1条回答
小情绪 Triste *
2楼-- · 2019-08-05 08:30

You need a converter to achieve this behavior.

public class CaseConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {            
        TextInfo textInfo = culture.TextInfo;
        return  textInfo.ToTitleCase(value.ToString());
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();;
    }
}

Add this as resource

<Window.Resources>
    <local:CaseConverter x:Key="MyCaseConverter"></local:CaseConverter>
</Window.Resources>

and use it in XAML as

<TextBlock Text="{Binding Name, Converter={StaticResource MyCaseConverter}}"/>
查看更多
登录 后发表回答