ComboBox, связанный с Enum с помощью IValueConverter, теряет SelectedItem

1

У меня есть combobox, связанный с перечислением, который отлично работает, но когда я использую IValueConverter чтобы сделать значение enum более дружественным, в IValueConverter больше не выбран по умолчанию элемент. Есть идеи?

[ValueConversion(typeof(InstallerAction), typeof(string))]
    public class InstallerActionConverter : IValueConverter
    {
        /// <summary>
        /// Converts a value.
        /// </summary>
        /// <param name="value">The value produced by the binding source.</param>
        /// <param name="targetType">The type of the binding target property.</param>
        /// <param name="parameter">The converter parameter to use.</param>
        /// <param name="culture">The culture to use in the converter.</param>
        /// <returns>
        /// A converted value. If the method returns null, the valid null value is used.
        /// </returns>
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var installerActions = (InstallerAction[])value;
            var result = new List<string>();

            foreach(var item in installerActions)
            {
                switch (item)
                {
                    case InstallerAction.Install:
                        result.Add("Install");
                        break;
                    case InstallerAction.None:
                        result.Add("None");
                        break;
                    case InstallerAction.UninstallAll:
                        result.Add("Uninstall All");
                        break;
                    case InstallerAction.UninstallOne:
                        result.Add("Uninstall One");
                        break;
                }
            }
            return result;
        }

        /// <summary>
        /// Converts a value.
        /// </summary>
        /// <param name="value">The value that is produced by the binding target.</param>
        /// <param name="targetType">The type to convert to.</param>
        /// <param name="parameter">The converter parameter to use.</param>
        /// <param name="culture">The culture to use in the converter.</param>
        /// <returns>
        /// A converted value. If the method returns null, the valid null value is used.
        /// </returns>
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var installerActions = (string)value;

            switch (installerActions)
            {
                case "None":
                    return InstallerAction.None;
                case "Install":
                    return InstallerAction.Install;
                case "Uninstall One":
                    return InstallerAction.UninstallOne;
                case "Uninstall All":
                    return InstallerAction.UninstallAll;
                default:
                    return InstallerAction.None;
            }
        }
    }

И XAML:

<ListView Name="ListView" ItemsSource="{Binding DatabaseInfos}" VerticalAlignment="Stretch" Margin="10">
                    <ListView.Resources>
                        <Style TargetType="ListViewItem">
                            <Style.Triggers>
                                <Trigger Property="Validation.HasError" Value="True">
                                    <Setter Property="Background" Value="Red" />
                                </Trigger>
                            </Style.Triggers>
                        </Style>
                    </ListView.Resources>
                    <ListView.View>
                        <GridView>
                            <GridViewColumn Header="Action">
                                <GridViewColumn.CellTemplate>
                                    <DataTemplate>
                                        <ComboBox Width="100" ItemsSource="{Binding Source={StaticResource ActionFromEnum}, Converter={StaticResource InstallerActionConverter}}" SelectedItem="{Binding Action}" />
                                    </DataTemplate>
                                </GridViewColumn.CellTemplate>
                            </GridViewColumn>

                            ...
  • 0
    ItemsSource имеет тип string, но SelectedItem все еще связан с enum. Оба должны быть согласованы, т. Е. Если ItemsSource имеет тип IEnumerable<T> , выбранный элемент должен иметь тип T
Теги:
wpf
enums
combobox

2 ответа

1
Лучший ответ

Примените конвертер к привязке SelectedItem.

  • 0
    В итоге я использовал два конвертера: один для ItemsSource ( MyEnum[] ) и один для SelectedItem ( MyEnum )
0

Вместо того чтобы использовать конвертер для привязки источника элемента и затем выбранного элемента, вы можете попробовать установить параметр Item Template для элемента combo box, чтобы отобразить дружественное имя.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню