Search code examples
xamlwindows-phonewin-universal-appuwpuwp-xaml

Resources with Binding's Converter


I have several string resources for different languages. As you can see, all of them starts with capitalized letter and then in lower case. So, is there any way how to Converter all of them to UPPERCASE without direct changing of resources? Is it possible to do it in XAML? Maybe combination of Binding's converter?

enter image description here


Solution

  • Here's a C# version of the same thing:

    public class ToUpperConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            string stringValue = value as string;
            return string.IsNullOrEmpty(stringValue) ? string.Empty : stringValue.ToUpper();
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            throw new NotSupportedException();
        }
    }
    

    To reference this in XAML:

    <Page
        x:Class="App1.MainPage"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="using:App1">
    
        <Page.Resources>
            <local:ToUpperConverter x:Key="UpperCaseConverter" />
        </Page.Resources>
    
        <StackPanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
            <TextBlock Text="{x:Bind MyString, Converter={StaticResource UpperCaseConverter}}" />
        </StackPanel>
    </Page>
    

    For completeness, this is the property I x:Bind to:

    public sealed partial class MainPage
    {
        public string MyString => "Hello world!";
    
        public MainPage()
        {
            InitializeComponent();
        }
    }
    

    EDIT

    In the comments of the OP, @RaamakrishnanA asks about how this might work with resources. A bit of indirection is one approach.

    In the .resw file, provide a value for the Tag property:

    <data name="HelloWorld.Tag">
      <value>Hello, world!</value>
    </data>
    

    Now use x:Uid to bind that to the Tag property of a TextBlock, then bind the Text property to the tag, allowing us to use the converter:

    <TextBlock
        x:Name="textBlock"
        x:Uid="HelloWorld"
        Text="{Binding Tag, ElementName=textBlock, Converter={StaticResource UpperCaseConverter}}"
    />
    

    Output:

    enter image description here