Original: WPF content data binding StringFormat How it works and solves
<window x:class= "WpfOne.Bind.Bind6" xmlns= "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xml ns:x= "Http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d= "http://schemas.microsoft.com/expression/blend/2008 "Xmlns:mc=" http://schemas.openxmlformats.org/markup-compatibility/2006 "xmlns:local=" clr-namespace:wpfone.b IND "xmlns:sys=" Clr-namespace:system;assembly=mscorlib "mc:ignorable=" D "title=" Bind6 "height=" W idth= > <Grid> <!--introduce the System namespace xmlns:sys= under the mscorlib assembly CLR-NAMESPACE:SYSTEM;ASSEMBLY=MSC Orlib "-<Grid.Resources> <sys:datetime x:key=" DateTime001 ">03/29/2016 15:05:30& lt;/sys:datetime> </Grid.Resources> <textbox text= "{Binding source={staticresource DateTime001}, STRINGFORMAT=DDDD, Mode=oneway} "height=" "horizontalalignment=" left "margin=" 28,68,0,0 "Na Me= "TextBox1" VERTICALALIGNMEnt= "Top" width= "/> <label content=" {Binding source={staticresource DateTime001}, STRINGFORMAT=DDDD, Mod E=oneway} "height=" "horizontalalignment=" left "margin=" 28,26,0,0 "name=" Label1 "verticalalignment=" Top " /> </Grid></Window>
The textbox displays the full English week as expected, but the label format does not change anything. We use exactly the same binding and format strings, where exactly is the difference? If you are careful enough, you can see that the binding of a TextBox is done on the Text property, and the binding of the label is on the content property.
Detailed analysis
Intrinsic reason: Control.content is an object type, and Binding.stringformat only works when the property type of the binding is string.
Through the binding process of the label below (from StackOverflow cattle), we can see the underlying details:
1. The binding binds the value of the DateTime type and assigns the value to Label.content.
2. The label's template contains ContentPresenter, which is used to display the content.
3. The label's ContentPresenter will look for contenttemplate,datatemplate to display the content in turn, and when this is not found, it will use the default template.
4. The default template used by ContentPresenter uses the Label.contentstringformat property to format object to string.
5. Note that the above is a streamlined process, essentially, ContentPresenter will display the results with its own template and StringFormat, but because during the label control loading process, The label's ContentTemplate and Contentstringformat are automatically bound to ContentPresenter ContentTemplate and StringFormat. The ContentPresenter essence is displayed with the label's ContentTemplate and Contentstringformat preference. So, here we say that cotentpresenter with the properties of the label is not a problem.
So, for content of non-string type, adding the attribute definition contentstringformat=dddd can show the results we need.
WPF content Data binding StringFormat the principles and solutions that work