Целые числа в поле со списком не привязывают данные - PullRequest
4 голосов
/ 23 августа 2011

У меня есть поле со списком размеров шрифтов, которые я пытаюсь связать с моделью представления MVVM.Свойство SelectedItem привязано к моему свойству модели Viwe, FontSize.Раскрывающийся список исправлен, поэтому я объявляю элементы поля со списком в XAML для поля со списком, например:

    <ComboBox SelectedItem="{Binding Path=FontSize, Mode=TwoWay, 
                             UpdateSourceTrigger=PropertyChanged}" 
              Width="60" Margin="2,0,3,0">
    <ComboBoxItem Content="10" />
    <ComboBoxItem Content="12" />
    <ComboBoxItem Content="18" />
    <ComboBoxItem Content="24" />
    <ComboBoxItem Content="36" />
    <ComboBoxItem Content="48" />
    <ComboBoxItem Content="60" />
    <ComboBoxItem Content="72" />
</ComboBox>

Вот моя проблема: при запуске приложения загружаются элементы со спискомхорошо.Но когда я выбираю элемент из списка, я получаю эту ошибку в окне «Вывод»:

Int32Converter cannot convert from System.Windows.Controls.ComboBoxItem.

Другие привязки данных в окне работают нормально.Полное сообщение об ошибке перепечатано ниже.

Что говорит мне сообщение об ошибке, и как мне это исправить?Заранее благодарим за помощь.


Полное сообщение об ошибке:

System.Windows.Data Error: 23 : Cannot convert 'System.Windows.Controls.ComboBoxItem: 12' from type 'ComboBoxItem' to type 'System.Int32' for 'en-US' culture with default conversions; consider using Converter property of Binding. NotSupportedException:'System.NotSupportedException: Int32Converter 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)'
System.Windows.Data Error: 7 : ConvertBack cannot convert value 'System.Windows.Controls.ComboBoxItem: 12' (type 'ComboBoxItem'). BindingExpression:Path=FontSize; DataItem='MainWindowViewModel' (HashCode=14640006); target element is 'ComboBox' (Name=''); target property is 'SelectedItem' (type 'Object') NotSupportedException:'System.NotSupportedException: Int32Converter cannot convert from System.Windows.Controls.ComboBoxItem.
   at MS.Internal.Data.DefaultValueConverter.ConvertHelper(Object o, Type destinationType, DependencyObject targetElement, CultureInfo culture, Boolean isForward)
   at MS.Internal.Data.ObjectTargetConverter.ConvertBack(Object o, Type type, Object parameter, CultureInfo culture)
   at System.Windows.Data.BindingExpression.ConvertBackHelper(IValueConverter converter, Object value, Type sourceType, Object parameter, CultureInfo culture)'

Ответы [ 2 ]

10 голосов
/ 24 августа 2011
  1. Установите SelectedValuePath на Content, это сделает SelectedValue Content выбранного ComboBoxItem.
  2. Свяжите SelectedValue со свойством виртуальной машины вместо SelectedItem.
<ComboBox
    Width="60"
    Margin="2,0,3,0"
    SelectedValuePath="Content"
    SelectedValue="{Binding FontSize}">

( Установка UpdateSourceTrigger и Mode не нужны, так как они установлены по умолчанию )

4 голосов
/ 23 августа 2011

Ваш ComboBox содержит ComboBoxItems, и вы связали selectedItem с целочисленным свойством, которое вызывает ошибки.Когда вы выбираете ComboBoxItem, он пытается установить ComboBoxItem как SelectedItem, но выдает ошибку при попытке привести его к целому числу.Я бы связал коллекцию целых чисел в вашей модели представления с ComboBox.ItemsSource, чтобы это исправить.Эта опция дает вам гибкость чтения списка из базы данных или файла.

<ComboBox SelectedItem="{Binding Path=FontSize, Mode=TwoWay, 
                         UpdateSourceTrigger=PropertyChanged}" 
          Width="60" Margin="2,0,3,0" ItemsSource="{Binding FontSizeList}"/>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...