-->

MultiBinding with binding StringFormat

2019-08-04 04:50发布

问题:

I am trying to display some label with MultiBinding with Binding on StringFormat.

Like that:

<Label.Content>
    <TextBlock>
        <TextBlock.Text>
            <MultiBinding StringFormat="{Binding LabelStringFormat, Source={DynamicResource Texts}}">
                <Binding Path="Lib1" />
                <Binding Path="Lib2" />
            </MultiBinding>
        </TextBlock.Text>
    </TextBlock>
</Label.Content>

LabelStringFormat can be something like "[{0}/{1}]" or something like that. It is known in build but must be used from Resource.

But when I use something like code above, I get error:

A 'Binding' cannot be set on the 'StringFormat' property of type 'MultiBinding'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject.

I can use binding on Content and create string in ViewModel, but it is unnoticed when there is more labels like this one.

Thanks Jakub

SOLUTION:

Use Convertor:

public class StringMultiValueConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return string.Format(values.Last() as string, values);
    }

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

In WPF add convertor to Resources:

<UserControl.Resources>
    <ResourceDictionary>
        <myComponents:StringMultiValueConverter x:Key="stringMultiValueConverter"/>
    </ResourceDictionary>
</UserControl.Resources>

In Label add:

<Label.Content>
    <TextBlock>
        <TextBlock.Text>
            <MultiBinding Converter="{StaticResource stringMultiValueConverter}">
                <Binding Path="Lib1" />
                <Binding Path="Lib2" />
                <Binding Path="LabelStringFormat" Source="{Dynamic Texts}"/>
            </MultiBinding>
        </TextBlock.Text>
    </TextBlock>
</Label.Content>

This work when string format is last param of Multibinding.

回答1:

Just add the "LabelStringFormat" as a parameter of the multi-binding:

<MultiBinding>
    <Binding Path="Lib1" />
    <Binding Path="Lib2" />
    <Binding Path="LabelStringFormat" Source="{DynamicResource Texts}" />
</MultiBinding>

Do the formatting from your IValueConverter using String.Format((string)values[2], values[0], values[1]).



回答2:

I don't think you need to use a Binding on the MultiBinding.StringFormat property. Instead, can you do something like this?

<Label.Content>
    <TextBlock>
        <TextBlock.Text>
            <MultiBinding StringFormat="{DynamicResource Texts.LabelStringFormat}">
                <Binding Path="Lib1" />
                <Binding Path="Lib2" />
            </MultiBinding>
        </TextBlock.Text>
    </TextBlock>
</Label.Content>