Binding StringFormat

前端 未结 3 659
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-06 01:12

I have a collection of textblocks that I\'m going to be showing and I\'m needing the text of each textblock to be displayed differently. I\'m currently saving the format str

相关标签:
3条回答
  • 2020-12-06 01:26
    <TextBlock>
        <TextBlock.Text>
            <MultiBinding StringFormat="{}{0},{1}">
                <Binding Path="MyProperty" />
                <Binding Path="MyFormatString" />
            </MultiBinding>
        </TextBlock.Text>
    </TextBlock>
    
    0 讨论(0)
  • 2020-12-06 01:32

    The String Formatting is a display setting and therefore should live close to the UI layer, you can either declare it in the Xaml or have formatted string properties on a ViewModel and perform the formatting in the Get of those properties and bind the TextBlock to it the ViewModel properties. It would source its data from the original datasource.

    0 讨论(0)
  • 2020-12-06 01:37

    Since BindingBase.StringFormat is not a dependency property, I do not think that you can bind it. If the formatting string varies, I'm afraid you will have to resort to something like this

    <TextBlock Text="{Binding MyFormattedProperty}" />
    

    and do the formatting in your view model. Alternatively, you could use a MultiBinding and a converter (example code untested):

    <TextBlock>
        <TextBlock.Text>
            <MultiBinding Converter="{StaticResource myStringFormatter}">
                <Binding Path="MyProperty" />
                <Binding Path="MyFormatString" />
            </MultiBinding>
        </TextBlock.Text>
    </TextBlock>
    
    public class StringFormatter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            return string.Format((string)values[1], values[0]);
        }
        ...
    }
    
    0 讨论(0)
提交回复
热议问题