【问题标题】:Format string is ignored after TextBox gets bound to a propertyTextBox 绑定到属性后忽略格式字符串
【发布时间】:2019-04-21 23:27:11
【问题描述】:

在动态构建的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 绑定到属性时使格式正常工作?

【问题讨论】:

  • 因为在 MakeTheBindings 中,您正在用一个新的绑定替换您的绑定。确保在执行此操作时 var binding = new Binding("Amount_QuotePos_Base");您还设置了所有属性,例如 ConverterCulture 和 StringFormat。
  • @Jon 我试过了,但仍然是相同的行为。在我的原始代码中,格式绑定是在绑定到属性之后设置的。所以它应该覆盖属性绑定并执行格式化。
  • @Jon,对不起,你是对的。我所要做的就是在我的MakeTheBindings() 中添加ConverterCulture = new System.Globalization.CultureInfo("de-DE"), StringFormat = "{0:#,##0.00}"。我会接受这个作为答案。非常感谢!
  • 很高兴!

标签: c# wpf dependency-properties


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-21
    • 1970-01-01
    • 2012-08-12
    • 1970-01-01
    • 1970-01-01
    • 2019-11-18
    • 1970-01-01
    • 2015-11-23
    相关资源
    最近更新 更多