How to do Binding Stackpanel and stringFormat?
I have some stackpanel that have under him 4 textblock that need to show some information. I do some binding of the stackpanel ( DataContext ) and binding the textblock with the information that will hold by the object that was bind to the 开发者_如何学Cstackpanel.
I wrote the code + xaml and nothing work. I get exception about format wrong.
The code:
public partial class SomeDemoClass: UserControl
{
classObjDemo c1;
public SomeDemoClass()
{
InitializeComponent();
c1 = new classObjDemo()
{
val1 = 5.5,
val2 = 2.3
};
}
}
The xaml ( that match the class 'SomeDemoClass' )
<StackPanel x:Name="LayoutRoot" DataContext="{Binding ElementName=SomeDemoClass, Path=c1">
<TextBlock Text="{Binding val1, StringFormat={0:F} }" />
<TextBlock Text="{Binding val2, StringFormat={0:F} }" />
</StackPanael>
Of you put x:Name="SomeDemoClass" in the in the op of your xaml and make c1 a public property instead of a field it would work. ElementName references elements in your xaml by name and binding only works on properties and dependency properties.
<UserControl x:Name="SomeDemoClass" ...
public classObjDemo c1 { get; set; }
Also check your Visual Studio output window for binding errors.
EDIT
Also make sure v1 and v2 of the classObjDemo are public properties
And escape { in your xaml. See http://elegantcode.com/2009/04/07/wpf-stringformat-in-xaml-with-the-stringformat-attribute/
<TextBlock Text="{Binding val2, StringFormat={}{0:F} }" />
精彩评论