简体   繁体   中英

How to implement a converter in WP8 using XAML and C# for capitalize the first letter of a word in a TexBlock?

I have a data template with a TexBlock in XAML. This TexBlock shows a word in a word list. Every word I want to put the first letter capitalized, because all words are in lowercase.

<phone:PhoneApplicationPage.Resources>
        <DataTemplate x:Key="AddrBookItemTemplate">
            <StackPanel VerticalAlignment="Top">
                <TextBlock Margin="5,0,0,0" FontSize="20" Text="{Binding name}" />
            </StackPanel>
        </DataTemplate>
 </phone:PhoneApplicationPage.Resources>

In c# implement the converter

namespace Converter.ViewModels

{

    public class ToCapitalizeConverter : IValueConverter
        {
            public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            {
                return char.ToUpper(value.ToString()[0]) + value.ToString().Substring(1);
            }

            public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            {
                return (value as string).ToLower();
            }
        }
}

In App.xaml

... xmlns:vm="clr-namespace:Converter.ViewModels"

   <Application.Resources>
          <vm:ToCapitalizeConverter x:Key="ToCapitalizeConverter"/>    
    </Application>

In MainPage.xaml

<phone:PhoneApplicationPage.Resources>
    <DataTemplate x:Key="AddrBookItemTemplate">
                <StackPanel VerticalAlignment="Top">
                    <TextBlock Margin="5,0,0,0" FontSize="20" Text="{Binding name, Converter={StaticResource ToCapitalizeConverter}}" />                 
                </StackPanel>
           </DataTemplate>
     </phone:PhoneApplicationPage.Resources>

You can use a converter as follows:

<TextBlock Margin="5,0,0,0" FontSize="20" Text="{Binding name, Converter ={StaticResource myConverter}}" />

Specific information on how to implement a converter can be found here . You can essentially perform any operation you like on the text. I actually like Humanizer to do these type of text conversions.

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