Jeremi Sharkboy
Jeremi Sharkboy

Reputation: 55

Dynamic values like digit at ResourceDictionary

For example i have smth like this

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:sys="clr-namespace:System;assembly=mscorlib">
    <sys:String x:Key="USERNAME_AUTH_CONTENT">User auth success</sys:String>
</ResourceDictionary>

and in code behind, sometimes, I use this

var text = findRes("USERNAME_AUTH_CONTENT");

Is it possible to make smth like this:

<ResourceDictionary
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:sys="clr-namespace:System;assembly=mscorlib">
    <sys:String x:Key="USERNAME_AUTH_CONTENT">User %username auth success</sys:String>
</ResourceDictionary>

and at codebehind

var text = findRes("USERNAME_AUTH_CONTENT", "here is i want to paste username");

in the end I want see this: 'User AwesomeUserName auth success'

In c++ I can use %d for string. What about c# and resources?

Upvotes: 0

Views: 105

Answers (1)

ASh
ASh

Reputation: 35723

C# uses {0}, {1}, etc, placeholders for string formatting.

declare xaml resource with a placeholder

<system:String x:Key="USERNAME_AUTH_CONTENT">User {0} auth success</system:String>

and use String.Format to apply formatting:

var text = FindResource("USERNAME_AUTH_CONTENT") as string;
if (text != null)
{
    text = String.Format(text, "AwesomeUserName");
}

note also that you can use format string directly from xaml:

<TextBlock Text="{Binding Source='AwesomeUserName', StringFormat={StaticResource USERNAME_AUTH_CONTENT}}"/>

(Source='AwesomeUserName' is just an example, if you have a view model, then use Binding Path=SomeProperty)

Upvotes: 1

Related Questions