Search code examples
wpfconvertersmultibindingstring-formatting

Applying a (non-multi) ValueConverter the output of a MultiBinding + StringFormat


Is there a way to apply a (single, not multi) ValueConverter to the output of a MultiBinding which uses StringFormat (i.e. after the string has been formatted).

It would be the equivalent of that code, in which I used an intermediary collapsed TextBlock to do the trick :

   <StackPanel>
        <TextBox x:Name="textBox1">TB1</TextBox>
        <TextBox x:Name="textBox2">TB2</TextBox>

        <TextBlock x:Name="textBlock" Visibility="Collapsed">
            <TextBlock.Text>
                <MultiBinding StringFormat="{}{0}{1}">
                    <Binding ElementName="textBox1" Path="Text"/>
                    <Binding ElementName="textBox2" Path="Text"/>
                </MultiBinding>
            </TextBlock.Text>
        </TextBlock>

        <TextBlock Text="{Binding ElementName=textBlock,
                   Path=Text, Converter={StaticResource SingleValueConverter}}" />

    </StackPanel>

Solution

  • Here is a hack that does what you want:

    public static class Proxy
    {
        public static readonly DependencyProperty TextProperty = DependencyProperty.RegisterAttached(
            "Text",
            typeof(string),
            typeof(Proxy),
            new PropertyMetadata(string.Empty));
    
        public static void SetText(this TextBlock element, string value)
        {
            element.SetValue(TextProperty, value);
        }
    
        [AttachedPropertyBrowsableForChildren(IncludeDescendants = false)]
        [AttachedPropertyBrowsableForType(typeof(TextBlock))]
        public static string GetText(this TextBlock element)
        {
            return (string) element.GetValue(TextProperty);
        }
    }
    

    <StackPanel>
        <TextBox x:Name="textBox1">TB1</TextBox>
        <TextBox x:Name="textBox2">TB2</TextBox>
    
        <TextBlock Text="{Binding Path=(local:Proxy.Text), 
                                  RelativeSource={RelativeSource Self}, 
                                  Converter={StaticResource SingleValueConverter}}">
            <local:Proxy.Text>
                <MultiBinding StringFormat="{}{0}{1}">
                    <Binding ElementName="textBox1" Path="Text" />
                    <Binding ElementName="textBox2" Path="Text" />
                </MultiBinding>
            </local:Proxy.Text>
        </TextBlock>
    </StackPanel>