首页 > 解决方案 > 将 Selected Combobox 项目转换为小数并将其存储在数据库中

问题描述

我的问题:我有一个组合框,其值为:11,251,351,451 和 551。我在 WPF 中使用 MVVM 模式,我想使用转换器,将所选值转换为小数并使用捆绑。

一旦我尝试转换该值,我的 Converter 中的 ConvertBack 方法就会出现以下异常。

这是我的转换器的代码:

        {
            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();
        }

这是我的组合框的 xaml 代码:

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

有什么值得注意的我做错了吗?

另一种解决方案是什么?

标签: c#wpfmvvm

解决方案


显然,您在 convert back 中抛出异常......但除此之外,还有很多问题。让我解释...

在转换器的方法中放置断点就足以ConvertBack看到要转换的值ComboBoxItem- 这不是您所期望的。

或者,查看输出窗口(如果您使用 Visual Studio),您还可以获得一些信息“内部”发生的应用程序:

System.Windows.Data Error: 23 : Cannot convert 'System.Windows.Controls.ComboBoxItem: 11' from type 'ComboBoxItem' to type 'System.Decimal' for 'en-US' culture with default conversions; consider using Converter property of Binding. NotSupportedException:'System.NotSupportedException: DecimalConverter cannot convert from System.Windows.Controls.ComboBoxItem.
   at System.ComponentModel.TypeConverter.GetConvertFromException(Object value)
   at System.ComponentModel.TypeConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)
   at System.ComponentModel.BaseNumberConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)
   at MS.Internal.Data.DefaultValueConverter.ConvertHelper(Object o, Type destinationType, DependencyObject targetElement, CultureInfo culture, Boolean isForward)'

因此,您应该绑定到视图模型中的集合,而不是定义组合项,这将保留小数 - 然后您只需绑定到选定的项目,无需转换任何内容。

所以你必须选择:

  1. 脏 - 在您的转换器中,修改代码以便它处理ComboboxItem而不是纯字符串(正如我可以从您的代码中假设的那样)。

  2. 清洁 MVVM 方式(@Clemens 建议):在您的视图模型项目源上定义

public ObservableCollection<decimal> CbxItems { get; } = new ObservableCollection<decimal>();

并在 XAML 中绑定到它:

<Combobox ItemsSource="{Binding CbxItems}" SelectedItem="{Binding MyDecimal}" />

推荐阅读