将数字字符串格式化为XAML中的特定小数位数

问题描述:

我有一个TextBlock,它绑定到一个字符串属性,这是一个化学数字。在我的视图中,我想将其格式化为小数点后的一位数。

我尝试了一些方法,但都没有用。任何想法都可能是错的或者还有什么可以尝试?



我尝试过:



I have a TextBlock that is binding to a string property which is a demical number. On my view i want to format it to one digit after decimal point.
I tried a few approaches but none worked. Any idea could be wrong or what else to try?

What I have tried:

My TextBlock xaml:
<TextBlock Grid.Row="5" Text="{Binding SelChem.Lel, StringFormat={}{0:F1}}"/>



我也尝试过:


I also tried:

<TextBlock Grid.Row="5" Text="{Binding SelChem.Lel, StringFormat=N2}"/>

您可以编写要在绑定中引用的转换器。例如:



You can write a converter to be referenced in the binding. For instance:

public class RoundMyNumberConverter : IValueConverter
{
    public object ConvertNumber(object value, Type targetType, object paramater, CultureInfo culture)
        {
            double result = 0;
            if (value != null && (double.TryParse(value.toString(), out result)))
                return Math.Round(result,1);
            else
                return value;
        }

    public object ConvertBack(object value, Type targetType, object paramater, CultureInfo culture)
        {
            return value;
        }
}





注:Math.Round(结果,1< - 这是多少个地方你想要小数后)所以转换器将接受绑定值,通过转换器运行它,然后显示创建的值。



然后你只需要在里面引用它xaml作为转换器。



注意:如果项目和装配在当前项目之外,请记住参考:



Note: The Math.Round(result, 1<- this is how many places you want after the decimal) so the converter will take in the binding value, run it through the converter and then display the value created.

Then you just reference this inside the xaml as a converter.

Note: Remember to reference your project and assembly if it is outside your current project like:

xmlns:cnvrtr="clr-namespace:MyConverterProject;assembly=MyConverterProject





您还需要将其列为UserControl或Grid中的资源?



Also you need to list it as a resource inside your UserControl or Grid?

<Grid>
    <Grid.Resources>
        <cnvrtr:RoundMyNumberConverter x:key="myConverter"/>
    </Grid.Resources>

    <TextBlock Grid.Row="5" Text="{Binding SelChem.Lel, Converter={StaticResource myConverter}}"/>
</Grid>





如果您有任何疑问,请告诉我们!



Let me know if you have anymore questions!