将TextBox绑定到属性后,将忽略格式字符串

问题描述 投票:0回答:1

在动态构建的UserControl中,我以这种方式为format string设置了TextBox

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; }
}

到目前为止工作正常。

但是在添加DependencyProperty之后,将忽略该格式。 Dependencyproperty以这种方式定义:

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);
    }
}

有没有办法在TextBox绑定到属性时使格式工作?

c# wpf dependency-properties
1个回答
1
投票

因为在MakeTheBindings()中,您将使用新的Binding替换Binding。确保执行此操作时var binding = new Binding(“Amount_QuotePos_Base”);您还设置了所有属性,如ConverterCulture和StringFormat

© www.soinside.com 2019 - 2024. All rights reserved.