Search code examples
c#windows-phone-8windows-phone

Binding StringFormat in Windows Phone


I develop silverlight app for windows phone 8. I bind integer value in LongListSelector for example 123. And I want to make it looks like 000123

<phone:LongListSelector ItemsSource="{Binding AllValues}">
  <phone:LongListSelector.ItemTemplate>   
    <DataTemplate>
     <StackPanel>
       <TextBlock x:Name="ValueBlock" 
                  Text="{Binding ValueValue}"
                  HorizontalAlignment="Left" 
                  VerticalAlignment="Center" 
                  Style="{StaticResource PhoneTextLargeStyle}"/>
...

I know StringFormat can do this, but the problem is number of leading zeros is always different and I want to bind it from ViewModel.

... 
Text="{Binding ValueValue}, StringFormat=\{0:D6\}"
...

How can I bind a number after D in StringFormat?


Solution

  • You can't bind the StringFormat part of a binding expression. What you can do instead is add another property to the view model like "ValueDisplay".

    public string ValueDisplay
    {
        get { return string.Format("{0:" + ValueFormat + "}", ValueValue); }
    }
    
    public string ValueFormat
    {
        get { return _valueFormat; }
        set
        {
            _valueFormat = value;
            RaisePropertyChanged("ValueDisplay");
        }
    }
    private string _valueFormat;