簡體   English   中英

XAML 文本框上的動態 StringFormat 通過 ViewModel 上的屬性

[英]Dynamic StringFormat on XAML TextBox via a property on the ViewModel

我有一個 XAML 視圖,其中 10 個 TextBox 綁定到我的 ViewModel 上的 10 個屬性。 我的 ViewModel 上的每個屬性都有一個與顯着數字值對應的屬性。 IE PropertyA 的有效數字值為 2。PropertyB 的有效數字值為 4。因此,在 UI 中,我希望將 PropertyA 顯示為 1.12,將 PropertyB 顯示為 1.4312。

有沒有辦法使用 StringFormat 綁定到 VM 上的 EffectiveDigit 值來限制顯示的小數位數?

例子。

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();
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM