0

データバインディング時に表示される文字列のフォーマットに問題があるだけです。

プロパティサイズがあるとします:

    /// <summary>
    /// Size information
    /// </summary>
    private long _size;
    public long Size
    {
        get
        {
            return _size;
        }
        set
        {
            if (value != _size)
            {
                _size = value;
                NotifyPropertyChanged("Size");
            }
        }
    }

このサイズは、バイト数を表す整数です。整数の大きさに応じてサイズを表す値を表示したい。例えば:

Size = 1 byte
Size = 1 kilobyte
Size = 100 megabytes

TextBlock の XAML は次のとおりです。

<TextBlock Text="{Binding Size, StringFormat='Size: {0}'}" TextWrapping="Wrap" Margin="12,110,0,0" Style="{StaticResource PhoneTextSubtleStyle}" Visibility="{Binding Visible}" FontSize="14" Height="20" VerticalAlignment="Top" HorizontalAlignment="Left" Width="200"/>

現時点では、50バイトを意味する「サイズ:50」と表示されていますが、「サイズ:50バイト/キロバイト/メガバイト」(適切なもののいずれか)を表示したいのですが、そうでない場合は「サイズ:50000000000000」と巨大になりますそんな数字。

文字列形式を「動的に」変更するにはどうすればよいですか?

テキストブロックは、ObservableCollection で囲まれた LongListSelector 内に含まれていることに注意してください。テキストブロックの形式を使用するオブジェクトのヒープがあるため、テキストブロックを取得してテキストを変更するだけでは機能しません。

ありがとう。

4

1 に答える 1

0

私の場合、ちょっとしたハックを使いました。ビューを、書式設定された値を含む追加の文字列プロパティを含む viewModel にバインドしています。たとえば、次のようなものです。

//using short scale: http://en.wikipedia.org/wiki/Long_and_short_scales#Comparison
const decimal HundredThousand = 100 * 1000;
const decimal Million = HundredThousand * 10;
const decimal Billion = Million * 1000; //short scale
const decimal Trillion = Billion * 1000; //short scale

const string NumberFormatKilo = "{0:##,#,.## K;- ##,#,.## K;0}";
const string NumberFormatMillion = "{0:##,#,,.## M;- ##,#,,.## M;0}";
const string NumberFormatBillion = "{0:##,#,,,.## B;- ##,#,,,.## B;0}";
const string NumberFormatTrillion = "{0:##,#,,,,.## T;- ##,#,,,,.## T;0}";

public decimal Size 
{
    get; set;
}

public string SizeFormatted 
{
    get 
    {
        var format = GetUpdatedNumberFormat(Size);
        return string.Format(format, Size);
    }
}

private static string GetUpdatedNumberFormat(decimal value)
{
    string format = NumberFormat;
    if (Math.Abs(value) >= Constants.Trillion)
        format = NumberFormatTrillion;
    else if (Math.Abs(value) >= Constants.Billion)
        format = NumberFormatBillion;
    else if (Math.Abs(value) >= Constants.Million)
        format = NumberFormatMillion;
    else if (Math.Abs(value) >= Constants.HundredThousand)
        format = NumberFormatKilo;
    return format;
}

次に、ビューをこのSizeFormattedプロパティにバインドします。

<TextBlock Text="{Binding SizeFormatted}" ...
于 2012-11-20T03:45:01.173 に答える