0

In a dynamically built UserControl I have set the format string for a TextBox this way:

TextBox newTextBox = new TextBox();

TempViewModel viewModel = new TempViewModel();
var binding = new System.Windows.Data.Binding
{
    Source = viewModel,
    Path = new PropertyPath("DecimalValue"),
    ConverterCulture = new System.Globalization.CultureInfo("de-DE"),
    StringFormat = "{0:#,##0.00}"
};

newTextBox.SetBinding(TextBox.TextProperty, binding);

public class TempViewModel
{
    public decimal DecimalValue { get; set; }
}

That works fine so far.

But after adding a DependencyProperty the format is ignored. The Dependencyproperty is defined this way:

public class UserControl_CBOGridQuotePositions : UserControl
{

    private static readonly DependencyProperty Amount_QuotePos_Base_DependencyProperty =
        DependencyProperty.Register("Amount_QuotePos_Base", typeof(System.Decimal), typeof(UserControl_CBOGridQuotePositions), new PropertyMetadata(0m));

    public System.Decimal Amount_QuotePos_Base
    {
        get { return (System.Decimal)GetValue(UserControl_CBOGridQuotePositions.Amount_QuotePos_Base_DependencyProperty); }
        set { SetValue(UserControl_CBOGridQuotePositions.Amount_QuotePos_Base_DependencyProperty, value); }
    }

    private void MakeTheBindings(DependencyProperty dependencyProperty)
    {
        var binding = new Binding("Amount_QuotePos_Base");
        binding.Source = this; // which is the UserControl_CBOGridQuotePositions

        newTextBox.SetBinding(dependencyProperty, binding);
    }
}

Is there a way to make the format working while the TextBox is bound to a property?

marsh-wiggle
  • 2,508
  • 3
  • 35
  • 52
  • Because in MakeTheBindings you are replacing your Binding with a new one. Make sure when you do this var binding = new Binding("Amount_QuotePos_Base"); that you also set all the properties such as ConverterCulture and StringFormat. – Jon Apr 21 '19 at 23:46
  • @Jon I tried that but still the same behaviour. In my original code the **format binding is set after the binding to the property**. So it should overwrite the property binding and perform the formatting. – marsh-wiggle Apr 22 '19 at 00:04
  • 1
    @Jon, sorry, you are right. All I have to do ist to add `ConverterCulture = new System.Globalization.CultureInfo("de-DE"), StringFormat = "{0:#,##0.00}"` in my `MakeTheBindings()`. I would accept this as answer. Many thanks! – marsh-wiggle Apr 22 '19 at 00:35
  • glad that worked! – Jon Apr 22 '19 at 00:55

1 Answers1

1

Because in MakeTheBindings() you are replacing your Binding with a new one. Make sure when you do this var binding = new Binding("Amount_QuotePos_Base"); that you also set all the properties such as ConverterCulture and StringFormat

Jon
  • 3,230
  • 1
  • 16
  • 28