I am trying to create a DataTemplate programmarically 100% in the codebehind. Everything works perfectly, except the StringFormat on the text binding in the textblocks doesn't work.
Normally in xaml, I would accomplish this like so:
<TextBlock Text={Binding MyProperty, StringFormat=0.0} /> so I assumed I could just set the StringFormat property of the Binding object, which I did. I verified that it gets set correctly, and it does, but my view still doesn't reflect the formatting. Why?
Here is an excerpt from my code: a function that creates a DataTemplate dynamically for me. Literally everything else works perfectly, from setting the binding path to the ivalue converters, and everything. Just not the string format.
string propertyName = "myPropertyName"; FrameworkElementFactory textBlock = new FrameworkElementFactory(typeof(TextBlock)); // the property I want is owned by myObject, which is a property of the datacontext string bindingString = String.Format("myObject[{0}]", propertyName); Binding binding = new Binding(bindingString) { Mode = BindingMode.OneWay, Converter = (IValueConverter)Application.Current.FindResource("InvalidValuesConverter"), StringFormat = "{0:F1}" // <-- Here is where I specify the stringFormat. I've also tried "0.0" }; textBlock.SetBinding(TextBlock.TextProperty, binding);