X:Bind and comma in double value

BitSmithy 2,186 Reputation points
2025-02-21T16:31:09.4+00:00

Hello,

I have such XAML

            <TextBox Text="{x:Bind FinancialItem2.Amount, Mode=TwoWay}" 
                     LostFocus="TextBox_LostFocus2"
                     />
            <TextBlock Text="{x:Bind FinancialItem2.Amount, Mode=OneWay}" />

and such code behind:

MainPage Initializer

            FinancialItem2 = new FinancialItem2();

            FinancialItem2.Amount = 123.45; // Example value

Definition in class

    public class FinancialItem2 : DependencyObject, INotifyPropertyChanged      
{          public static readonly DependencyProperty AmountProperty =

            DependencyProperty.Register("Amount", typeof(double), typeof(FinancialItem2), new PropertyMetadata(0.0));

        public double Amount

        {

            get { return (double)GetValue(AmountProperty); }

            set { 

                if(value is double)

                {

                    SetValue(AmountProperty, value);

                }

                else

                {

                    SetValue(AmountProperty, 0);

                }

            }

            //ValidateAmount();

        }

}


In Windows settings I use double with comma setting for example 12,5 as 12.5.

Now if I type in text box12,5 x:bind truncates its to 12. If I use Double.TryParse() for TextBox.text it finds the text as proper double.

How to fix this strange behavior?

Universal Windows Platform (UWP)
{count} votes

Accepted answer
  1. Junjie Zhu - MSFT 20,681 Reputation points Microsoft External Staff
    2025-02-26T08:52:44.8433333+00:00

    Hello @BitSmithy ,

    So, You confirm that it is rather x:Bind problem than my mistake, and walkthrought is needed?

    You just didn't do the string to double conversion in your code, in UWP you can use more appropriate controls.

    According to the current scenario, it is recommended that you use WinUI2 Number box. NumberBox.Text and NumberBox.Value make it easy to capture the value of a NumberBox as a String or as a Double without needing to convert the value between types. When programmatically altering the value of a NumberBox, it is recommended to do so through the Value property. Value will overwrite Text in initial set up. non-numeric characters through Text.

    <NumberBox Value="{x:Bind Path=ViewModel.NumberBoxValue, Mode=TwoWay}" />
    

    Thank you.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.