3

I tried to convert upper case to lower case by XAML in WPF like below:

<TextBox Height="86" CharacterCasing="Upper"/>

I want to achieve the same scenario with TextBlock, Label and Button.

How can I do it?

Askolein
  • 3,250
  • 3
  • 28
  • 40
CHANDRA
  • 4,778
  • 8
  • 32
  • 51

3 Answers3

9

You should use a value converter:

public class ToUpperValueConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var str = value as string;
        return string.IsNullOrEmpty(str) ? string.Empty : str.ToUpper();
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return null;
    }
}
Igor Popov
  • 9,795
  • 7
  • 55
  • 68
David Blurton
  • 150
  • 1
  • 9
  • 1
    would be nice to add how to use it in xaml, especially when binding resources as text. https://stackoverflow.com/a/1762678/2901207 – CularBytes Oct 03 '19 at 15:33
3

One way is to do this is to use NotifyOnTargetUpdated and handle TextChanged event.

XAML

<TextBlock Name="TB" Text="{Binding Path=YourProperty, NotifyOnTargetUpdated=True}"
               TargetUpdated="TB_TargetUpdated" />

Code behind

private void TB_TargetUpdated(object sender, DataTransferEventArgs e)
{
   TB.Text = TB.Text.ToUpper();
}
Anatoliy Nikolaev
  • 22,370
  • 15
  • 69
  • 68
Ramin
  • 2,133
  • 14
  • 22
  • You could do that but its quite case-specific - you would need to do that for every control. Much better to use _value converters_ as **David Button** mentions on this page. Not only are they re-usable but it is the WPF-way of doing things. –  Jan 16 '14 at 02:43
0

Just take a look at that: How to make all text upper case / capital?.

More generally, each time you want to transform a value to go into a control, think of a converter and write it yourself (or use it if it already exists).

You can find additional documentation on converters here: http://wpftutorial.net/ValueConverters.html.

Community
  • 1
  • 1
Qortex
  • 7,087
  • 3
  • 42
  • 59