Why does a format string that works in a Binding not work in a MultiBinding?
I was intrigued by this question: MultiBinding StringFormat of TimeSpan
If I have the following Binding defined where StartTime is of type TimeSpan:
<TextBlock Text={Binding Path=StartTime, StringFormat='{}From {0:hh\\:mm}'}" />
The above binding evaluates as expected. However, as the scenario in the original question sho开发者_JS百科ws, if I try to use the same format string in a MultiBinding, it fails with a FormatException:
<TextBlock>
<TextBlock.Text>
<MultiBinding StringFormat="{}From {0:hh\\:mm} to {1:hh\\:mm}">
<Binding Path="StartTime" />
<Binding Path="EndTime" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
The question is, does anyone know why? Is this a bug or expected behavior? It seems odd to me that to get the same output in a MultiBinding, I have to change the "\:" to a ':' in the format string (as I discovered in answering the original question).
This appears to be a bug in WPF 4, if not it's at least a breaking change from WPF 3.5. Take the following code for example:
<Window x:Class="WpfSampleTestBed.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<TextBlock Text="{Binding Path=StartTime, StringFormat='{}From {0:hh\\:mm}'}" />
<TextBlock x:Name="textBlock2">
<TextBlock.Text>
<MultiBinding StringFormat="{}From {0:hh\\:mm} to {1:hh\\:mm}">
<Binding Path="StartTime" />
<Binding Path="EndTime" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
<TextBlock x:Name="textBlock3" Text="Three" />
<TextBlock x:Name="textBlock4" Text="Four" />
<TextBlock>
<TextBlock.Text>
<MultiBinding StringFormat="Three = {0}, Four = {1}">
<Binding ElementName="textBlock3" Path="Text" />
<Binding ElementName="textBlock4" Path="Text" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</StackPanel>
</Window>
With the code behind like:
using System;
using System.Windows;
namespace WpfSampleTestBed {
public partial class MainWindow : Window {
public MainWindow() {
InitializeComponent();
this.DataContext = new Test() {
StartTime = TimeSpan.FromSeconds(90),
EndTime = TimeSpan.FromSeconds(100),
};
}
}
public class Test {
public TimeSpan StartTime { get; set; }
public TimeSpan EndTime { get; set; }
}
}
If you compile and run this code against .NET 3.5, the output (i.e. Window content) will look like this:
From 00:01:30
From 00:01:30 to 00:01:40
Three
Four
Three = Three, Four = Four
Taking the exact sample code/project and running it against .NET 4 you get:
From 00:01:30
Three
Four
Three = Three, Four = Four
I found one bug report that may be related, but the author never responded so Microsoft closed the issue as 'Not Reproducible'.
So it appears that depending on the how the child Bindings are used, the StringFormat may or may not work in .NET 4.
精彩评论