简体   繁体   中英

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

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>

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}}" />

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.

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:

屏幕截图

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