Search code examples
c#.netwpfmultibinding

StringFormat for DateTime is not working with MultiBinding


I have this code :

<Label>
    <Label.Content>
        <TextBlock>
            <TextBlock.Text>
                <MultiBinding StringFormat="{} created on {0} by">
                    <Binding Path="CreationDate" StringFormat="{}{0:dd/MM/yyyy}" />
                </MultiBinding>
            </TextBlock.Text>
        </TextBlock>
    </LabeledLabel.Content>
</Label>

OUTPUT

I always get this created on 21/09/2014 00:00:00 by

I tried StringFormat="d", but it didn't work too.

What's the problem with my code ?


Solution

  • You've only got one Binding Path, so you'll only ever get the date and time. Basically, you need to add a Binding element for your person data type. It should be more like this:

    <Label>
        <Label.Content>
            <TextBlock>
                <TextBlock.Text>
                    <MultiBinding StringFormat="{} created on {0:dd/MM/yyyy} by {1}">
                        <Binding Path="CreationDate" />
                        <Binding Path="SomeEmployeeObject.Name" />
                    </MultiBinding>
                </TextBlock.Text>
            </TextBlock>
        </LabeledLabel.Content>
    </Label>
    

    Note that you can also set the DateTime StringFormat using the MultiBinding.StringFormat property, instead of adding another on the first Binding object. You also needed to add the {1} to the end of the MultiBinding.StringFormat so that it would output the second (person related) value.

    Please see the MultiBinding Class page on MSDN for further information.


    UPDATE >>>

    I don't understand why putting the StringFormat property on the MultiBinding element has a different behaviour compared to the first element

    It doesn't... I could have left it there, but I moved it because you were already using a StringFormat. Using StringFormat property on a MultiBinding is virtually the same as using the string.Format method. Using the method, this is equivalent to what you had in your XAML:

    string.Format("created on {0:dd/MM/yyyy} by ", someDate);
    

    And this is equivalent to what I put in your XAML:

    string.Format("created on {0:dd/MM/yyyy} by {1}", someDate, someEmployee.Name);
    

    Hopefully, you can now see the difference.