Robert Seder
Robert Seder

Reputation: 1420

How to format a string in XAML where a binding is being used?

In WPF, I could do something like this:

<TextBlock Text="{Binding Products.Count, StringFormat='{0} Products'}"

What is the equivalent in Windows 8 / WinRT, as this syntax is no longer supported?

Upvotes: 7

Views: 4460

Answers (2)

Jakub Krampl
Jakub Krampl

Reputation: 1794

You can use this:

<TextBlock>
    <Run Text="{Binding Path=Products.Count}" />
    <Run Text=" Products" />
</TextBlock>

Upvotes: 8

nemesv
nemesv

Reputation: 139748

Based on the documentation on MSDN this functionality (e.g StringFormat on the Binding class) is not existing in WinRT.

So do the formatting on your ViewModel

public class MyViewModel
{
    public IList<Product> Products { get; set; }

    public string ProductsText 
    { 
        get 
        { 
            return string.Format("{0} Products", Products.Count); 
        } 
    }
}

Note you can hook to track changes in your Products collection and notify the ProductsText property changed.

And bind to formatted property:

<TextBlock Text="{Binding ProductsText}" />

Upvotes: 3

Related Questions