Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
128 views
in Technique[技术] by (71.8m points)

c# - Convert Selected Combobox item to a decimal and store it in the database

My problem: I have a Combobox, with the values of : 11,251,351,451 and 551. I am using the MVVM pattern in WPF, and I want to use a converter, to convert the selected value to a decimal and save it to the database using the binding.

As soon as I try to convert the value, I get the following exception on my ConvertBack Method in my Converter.

Here is the code for my Converter:

        {
            try
            {
                string str_value = value.ToString();
                decimal decimal_myvalue = decimal.Parse(str_value);
                return decimal_myvalue;

            }
            catch (Exception e)
            {

                var a = e.Message;
            }
            return 0;
            
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }

here is my xaml code for my combobox:

<ComboBox SelectedValue="{Binding Transaction.PoisonSeeds, Converter={StaticResource PoisonSeedValueConverter}}" ...>
    <ComboBoxItem Content="11"/>
    <ComboBoxItem Content="251"/>
    <ComboBoxItem Content="351"/>
    <ComboBoxItem Content="451"/>
    <ComboBoxItem Content="551"/>
</ComboBox>

is there anything noticable that I am doing wrong?

what can another solution be?

question from:https://stackoverflow.com/questions/65952338/convert-selected-combobox-item-to-a-decimal-and-store-it-in-the-database

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should use the ConvertBack method instead of the Convert, since you are writing to the Source

In Convert you should go from decimal to string.

In 'ConvertBack' you should convert from string to decimal

And as @Clements has pointed out: add SelectedValuePath="Content"


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...