c# - 将 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>
有什么值得注意的我做错了吗?
另一种解决方案是什么?
解决方案
显然,您在 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)'
因此,您应该绑定到视图模型中的集合,而不是定义组合项,这将保留小数 - 然后您只需绑定到选定的项目,无需转换任何内容。
所以你必须选择:
脏 - 在您的转换器中,修改代码以便它处理
ComboboxItem
而不是纯字符串(正如我可以从您的代码中假设的那样)。清洁 MVVM 方式(@Clemens 建议):在您的视图模型项目源上定义
public ObservableCollection<decimal> CbxItems { get; } = new ObservableCollection<decimal>();
并在 XAML 中绑定到它:
<Combobox ItemsSource="{Binding CbxItems}" SelectedItem="{Binding MyDecimal}" />
推荐阅读
- jquery - Laravel:如何使用 jQuery 验证来测试数据库中是否已经存在某些内容
- c# - 是否可以将 XAML 资源字典样式转换为与 c# 等效的样式?
- javascript - 未捕获的 RangeError:超过最大调用堆栈大小 Javascript
- java - 在java中获取绝对路径的最后一个元素有更好的方法吗?
- javascript - 从html响应nodejs中提取文本值
- amazon-web-services - Ubuntu 16.04,Couchbase 服务器,内部 ip 被解析为外部客户端
- .net - 从 C++ 中的 SortedDictionary 迭代时删除项目
- json - 删除 Json 编码额外的括号
- javascript - 向可观察响应添加附加参数
- postgresql - 如何恢复 postgres 备份 - 错误:无法删除当前打开的数据库