簡體   English   中英

DevExpress的TextEdit控件上的FormatException無法存儲我的十進制值

[英]FormatException on DevExpress' TextEdit control that can't store my decimal value

我有一個DevExpress(此問題我將其稱為“ DX”)控件TextEdit

這是我所擁有的樣品

<Grid>
    <dxe:TextEdit x:Name="te" MaskType="Numeric" Mask="###,##0.###"
                  MaskUseAsDisplayFormat="True" Validate="te_Validate"
                  Text="{Binding myValeur, UpdateSourceTrigger=PropertyChanged}"/>
</Grid>

掩碼Mask="###,##0.###"是正常的,我限於9個數字和3個小數。

我在我的代碼背后

decimal myDecimalValue = 0.0m;
private void te_Validate(object sender, DevExpress.Xpf.Editors.ValidationEventArgs e)
{
    Thread Thread_te_Validate = new Thread(delegate()
    {
        this.Dispatcher.BeginInvoke(new Action(delegate()
        {
            if (!String.IsNullOrEmpty(te.Text))
                myDecimalValue = Convert.ToDecimal(te.Text);
        }));
    });
    Thread_te_Validate.IsBackground = true;
    Thread_te_Validate.Start();
}

這段代碼有一個奇怪的問題。 如果我在TextEdit中寫100 ,則值將正確轉換。 如果我寫了100.123 (所以我放了一些小數),則應用程序崩潰,錯誤FormatException was unhandled by user code (法語翻譯)

詳細來說,我有{"The format of the input string is incorrect."}

崩潰時TextEdit.Text的值為100.123但十進制僅存儲100

我是法國人,使用的是法國文化,因此'逗號'是UI的小數點分隔符,但變量在小數點分隔符中正確存儲了'點'。

編輯:我測試此代碼,同樣的錯誤。 所以我認為問題是轉換為十進制。 string使用小數位數獲取值,但存在轉換錯誤。

if (!String.IsNullOrEmpty(te.Text))
{ 
    string test1 = te.Text;
    myDecimalValue = Convert.ToDecimal(test1);
}

編輯2:此代碼也不會啟動。

if (!String.IsNullOrEmpty(te.Text))
{ 
    string test1 = te.Text;
    myDecimalValue = decimal.Parse(test1);
}

編輯3:我也嘗試在轉換過程中強制文化。 使用此代碼,我無法在TextEdit中插入小數,只能輸入整數。

myDecimalValue = Convert.ToDecimal(te.Text, CultureInfo.InvariantCulture);

我的特定區域性發送FormatException錯誤。

myDecimalValue = Convert.ToDecimal(te.Text, CultureInfo.CreateSpecificCulture("fr-FR"));

我的中性文化也發送FormatException錯誤。

myDecimalValue = Convert.ToDecimal(te.Text, CultureInfo.CreateSpecificCulture("fr"));

適用於我的解決方案:此代碼適用於我。 我在App.xaml中將“語言”定義為“ fr”,但是顯然,它不夠。 因此,問題實際上是文化,當然還有小數字符。

對我來說,我需要用“逗號”代替“點”,因為DevExpress中的文化向我展示了良好的文化,但向我展示了美國文化。

if (!String.IsNullOrEmpty(myDXTextEdit.Text))
    myDecimalValue = Convert.ToDecimal(myDXTextEdit.Text.Replace(".", ","));

默認情況下,無論系統設置如何,WPF都使用en-US作為區域性。 我相信您沒有重寫此行為,而且您在TextEdit.Mask中將“點”作為小數點分隔符包括在內。 到現在為止還挺好。 那是因為您已經收到100.23 (帶“點”十進制分隔符)作為值。 但是,十進制轉換使用您當前的區域性( French )作為IFormatProvider因此您不能使用此區域性將文本轉換為十進制值(這是異常的原因)。

為避免發生異常,請指定正確的轉換區域性(您可以使用InvariantCulture而不是en-US ):

myDecimalValue = Convert.ToDecimal(te.Text, CultureInfo.InvariantCulture);

經過大量研究,結果發現存在兩個問題。

首先,在TextEdit修改的變量上進行TextEdit的綁定,這些變量創建了奇怪的循環並輸入了十進制錯誤。

其次,即使我的應用程序是在法國文化中定義的,它也必須強制使用String.Replace (".", "")才能正確執行轉換。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM