Dom Sinclair
Dom Sinclair

Reputation: 2528

Converting Text to ProperCase in wpf

I'm creating a wpf control with the odd text box on it for which I wish the text to be converted to Proper Case.

To that end I have created a converter;

Public Class TextToPropperCaseConverter
Implements IValueConverter


Public Function Convert(value As Object, targetType As Type, parameter As Object, culture As Globalization.CultureInfo) As Object Implements IValueConverter.Convert
    Dim txt As String = TryCast(parameter, String)
    If Not String.IsNullOrEmpty(txt) Then
        Return StrConv(txt, VbStrConv.ProperCase)
    Else
        Return txt.ToString
    End If
End Function

Public Function ConvertBack(value As Object, targetType As Type, parameter As Object, culture As Globalization.CultureInfo) As Object Implements IValueConverter.ConvertBack
    Return Nothing
End Function
End Class

and then gone on to reference in on the relevant text box in my xaml like so;

 <wizard:AeroWizardWindow.Resources>
    <local:TextToPropperCaseConverter x:Key="txtToPcase"/>
</wizard:AeroWizardWindow.Resources>

<TextBox Grid.Column="1" HorizontalAlignment="Left" Height="62" Margin="8,8,0,0" Grid.Row="1" TextWrapping="Wrap"  Text="{Binding Address, Converter={StaticResource txtToPcase}}" AcceptsReturn="True" VerticalAlignment="Top" Width="232"/>

Perhaps somewhat naively I was expected the text entered in the text box to change either as the user typed or better as the control lost focus, but nothing happened.

Is this the correct way to be doing this, or is this perhaps, despite the fact that I'm using MVVM and trying to avoid code behind, a classic example of where code behind would actually be better?

Many Thanks

Upvotes: 0

Views: 158

Answers (1)

Bas
Bas

Reputation: 27105

If you want to implement the conversion from user input to a ViewModel property you need to implement ConvertBack. See also the documentation for that. You return Nothing, this means that no matter what you type in the TextBox, Nothing will always be the resulting value from using the converter.

Upvotes: 1

Related Questions