StringFormat in XAML

一个人想着一个人 提交于 2019-12-07 02:30:17

问题


I am trying to format my string to have commas every 3 places, and a decimal if it is not a whole number. I have checked roughly 20 examples, and this is the closest I have come:

<TextBlock x:Name="countTextBlock" Text="{Binding Count, StringFormat={0:n}}" />

But I get a The property 'StringFormat' was not found in type 'Binding'. error.

Any ideas what is wrong here? Windows Phone 8.1 appears to differ from WPF, because all of the WPF resources say that this is how it is done.

(The string is updated constantly, so I need the code to be in the XAML. I also need it to remain binded. Unless of course I cannot have my cake and eat it too.)


回答1:


It seems that, similar to Binding in WinRT, Binding in Windows Phone Universal Apps doesn't have StringFormat property. One possible way to work around this limitation is using Converter as explained in this blog post,

To summarize the post, you can create an IValueConverter implmentation that accept string format as parameter :

public sealed class StringFormatConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        if (value == null)
            return null;

        if (parameter == null)
            return value;

        return string.Format((string)parameter, value);
    }

    public object ConvertBack(object value, Type targetType, object parameter,
        string language)
    {
        throw new NotImplementedException();
    }
}

Create a resource of above converter in your XAML, then you can use it like this for example :

<TextBlock x:Name="countTextBlock" 
           Text="{Binding Count, 
                          Converter={StaticResource StringFormatConverter},
                          ConverterParameter='{}{0:n}'}" />


来源:https://stackoverflow.com/questions/24966425/stringformat-in-xaml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!