繁体   English   中英

TextBox:绑定为double,通过IMultiValueConverter转换:ViewModel中的值更改时不更新

[英]TextBox: bound to double, converted via IMultiValueConverter: not updated when value changed in ViewModel

我正在使用Caliburn.Micro。

在我的视图中,我有一个绑定到double XTextBox和一个将X更改为我的ViewModel的Button

public void ButtonPressed()
    {
        X = AnObject.GetDouble;
        NotifyOfPropertyChange(() => X);
    }

    public double X { get; set; }

我的目标是限制显示的小数位数。 此数字可在应用程序中配置,因此可以作为AnObject的属性使用。 因此,我定义了一个IMultiValueConverter

public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        return String.Format(values[1].ToString(), values[0]);
    }

并定义我的TextBox如下:

<TextBox>
     <TextBox.Text>
           <MultiBinding Converter="{StaticResource coordinateConverter}" >
                 <Binding Path="X" />
                 <Binding Path="AnObject.FormatNumberOfDecimals" />
           </MultiBinding>
     </TextBox.Text>
</TextBox>

有效的方法: X的初始值零被正确格式化。

不起作用:按下按钮时,新值未在TextBox中显示。

也欢迎不使用IMultiValueConverter的建议。

事实证明,我的string FormatNumberOfDecimals的格式应为{0:0.0000}而不是0.00000

0.0000适用于Label的ContentStringFormat,并且在我的Visual Studio Designer中不会导致异常,但是当使用String.Format()时,显然不适用于TextBox。

{0:0.0000}适用于Label的ContentStringFormat以及使用String.Format()我的TextBox。 不幸的是,我的Visual Studio设计视图现在引发异常,并且对我的TextBox视图没有用。

System.FormatException
Input string was not in a correct format.
at System.Text.StringBuilder.AppendFormat(IFormatProvider provider, String format, Object[] args)
at System.String.Format(IFormatProvider provider, String format, Object[] args)
at System.String.Format(String format, Object arg0)

我过去也遇到过这样的问题,其中一个绑定值更新时, MultiConverter不会自动更新。

由于您没有为第二个值使用绑定,因此可以切换到单个IValueConverter ,并将格式作为ConverterParameter传入

或者只是使用绑定的StringFormat属性

<TextBox Text="{Binding X, StringFormat=D4}" />

请注意,如果要绑定Content属性而不是Text属性(例如在Label ,则绑定的StringFormat属性将不起作用,而您需要设置Label的ContentStringFormat属性。

那是工作

十进制借记= 0; 小数点数= 0;

        decimal.TryParse(values[0].ToString(), out debit);
        decimal.TryParse(values[1].ToString(), out credit);

        decimal total = debit - credit;

        return total.ToString("0.00"); // string form 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM