XAML TextBox 上的动态 StringFormat 通过 ViewModel 上的 属性

Dynamic StringFormat on XAML TextBox via a property on the ViewModel

我有一个 XAML 视图,其中 10 个文本框绑定到我的 ViewModel 上的 10 个属性。我的 ViewModel 上的每个属性都有一个对应的 属性 到 SignificantDigits 值。 IE PropertyA 的有效数字值为 2。PropertyB 的有效数字值为 4。因此在 UI 中,我想将 PropertyA 显示为 1.12,将 PropertyB 显示为 1.4312。

有没有办法使用 StringFormat 绑定到 VM 上的 SignificantDigit 值以限制显示的小数位数?

示例。

PropertyA = 1.231231;
PropertyB = 1.234234;

PropertyASignificantDigits = 2;
PropertyBSignificant Digits = 4;

<TextBox  Text="{Binding PropertyA, StringFormat={}{0:{PropertyASignificantDigits}}" TextAlignment="Center" />

然后 UI 将为 PropertyA 显示 1.23

如果我可以在 xaml

中管理它,我宁愿不使用转换器

您可以使用 MultiBinding 和 IMultiValueConverter 来完成此操作。

MultiBinding 接受您的值和小数位数,然后使用自定义多值转换器对值执行 string.Format,返回结果。

这是一个简单的例子:

XAML

<TextBox>
    <TextBox.Text>
        <MultiBinding Converter="{StaticResource DecimalPlaceStringFormatConverter}">
            <Binding Path="PropertyAValue" />
            <Binding Path="PropertyADecimalPlaces" />
        </MultiBinding>
    </TextBox.Text>
</TextBox>

转换器

public class DecimalPlaceStringFormatConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        string result = null;

        if (values.Length == 2 && values[0] is double value && values[1] is int decimalPlaces)
        {
            result = string.Format($"{{0:F{decimalPlaces}}}", value);
        }

        return result;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

感谢 Keithernet,我的答案是你不能在 XAML 内直接执行此操作,需要使用转换器。使用他的回答,这就是我最终转换器的样子

public class DecimalPlaceStringFormatConverter : IMultiValueConverter
    {
        public object Convert( object[] values, Type targetType, object parameter, CultureInfo culture )
        {
            if( !decimal.TryParse( values[ 0 ].ToString(), out decimal value ) )
                return values[ 0 ].ToString();

            if( !int.TryParse( values[ 1 ].ToString(), out int decimalPlaces ) )
                return value;

            if( values.Length == 2 )
                return string.Format( $"{{0:F{decimalPlaces}}}", value );
            else
                return value;
        }

        public object[] ConvertBack( object value, Type[] targetTypes, object parameter, CultureInfo culture )
        {
            throw new NotImplementedException();
        }
    }