Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF: How to shift Unicode character into a shared resource?

Tags:

c#

wpf

I have this XAML:

<TextBlock Text="Message with unicode char: &#x24D8;"/>

Is there some way to shift that unicode character &#x24D8; into a shared resource (like a constant or a StaticResource)?

What I have tried

Method 1

This works fine, but it requires a valid binding to work:

<Grid>
    <Grid.Resources>
        <system:String x:Key="ToolTipChar">{0} &#x24D8;</system:String>
    </Grid.Resources>
    <TextBlock Text="{Binding MyText, StringFormat={StaticResource ToolTipChar}}"/>
</Grid>

And in code behind:

public string MyText { get; set; } = "Message with unicode char: ";    

Method 2

This method seems like it might work, but no luck:

<Grid>
    <Grid.Resources>
        <system:String x:Key="ToolTipChar">{0} &#x24D8;</system:String>
    </Grid.Resources>
    <TextBlock Text="{Binding Nothing, FallbackValue='Message with unicode char: ', StringFormat={StaticResource ToolTipChar}}"/>
</Grid>
like image 264
Contango Avatar asked Dec 11 '17 14:12

Contango


3 Answers

If I understand your question correctly, this should work:

<Window.Resources>
    <s:String x:Key="ToolTipChar">{0}&#x24D8;</s:String>
</Window.Resources>
...
<TextBlock Text="{Binding Source='Message with unicode char:', StringFormat={StaticResource ToolTipChar}}" />
like image 198
mm8 Avatar answered Nov 18 '22 19:11

mm8


This will also work:

<Window.Resources>
    <system:String x:Key="ToolTipChar">&#x24D8;</system:String>
</Window.Resources>
...
<TextBlock Text="{Binding StringFormat='Message with unicode char: {0}', 
                          Source={StaticResource ToolTipChar}}" />

I find it slightly more readable, and easier to understand, than putting the replacement token directly in the string resource.

like image 38
Bradley Uffner Avatar answered Nov 18 '22 18:11

Bradley Uffner


Another alternative which doesn't involve binding is to use TextBlock.Inlines

<my:String x:Key="TooltipSign">&#x24D8;</my:String>
<TextBlock HorizontalAlignment="Right" Margin="10">
    <Run Text="Message with unicode char:"/>
    <Run Text="{StaticResource TooltipSign}" 
         FontWeight="Bold" Foreground="Orange" Background="Black"/>
</TextBlock>

TextBlock.Inlines is a content property of TextBlock, so <TextBlock.Inlines> tag can be omitted. Inlines provide additional decorating possibilities, like coloring part of the text:

screenshot

like image 2
ASh Avatar answered Nov 18 '22 18:11

ASh