SelectedValuePath не работает в выпадающем списке, когда ItemSource связан с конвертером - PullRequest
0 голосов
/ 07 марта 2020

У меня есть класс следующим образом:

public class VmUserNotification : BindableBaseThreadSafe
{
  private string _username;
        private EnumLocalizer<NotificationLevel> _notificationLevel;
        private List<EnumLocalizer<NotificationLevel>> _notificationOptions;

 public string Username
        {
            get => _username;
            set => Set(ref _username, value);
        }

        public EnumLocalizer<NotificationLevel> NotificationLevel
        {
            get => _notificationLevel;
            set => Set(ref _notificationLevel, value);
        }

        public List<EnumLocalizer<NotificationLevel>> NotificationOptions
        {
            get => _notificationOptions;
            set => Set(ref _notificationOptions, value);
        }
}

Теперь у меня есть другой класс, который реализует описанный выше класс:

 public class VmUserNotificationWithAllRoles : VmUserNotification
        {
        }

В ViewModel у меня есть ObservableCollection VmUserNotificationWithAllRoles. Я заполняю его следующим образом:

foreach (var user in usersWithNotificationLevelsOtherThanNone)
                {
                    var allOptions = new List<EnumLocalizer<NotificationLevel>>();
                    Enum.GetValues(typeof(NotificationLevel)).Cast<NotificationLevel>().ToList().ForEach(
                        logEventLevel => allOptions.Add(new EnumLocalizer<NotificationLevel>() { Value = logEventLevel }));

                    AlertSettings.UserNotificationListWithAllRoles.Add(new VmUserNotificationWithAllRoles()
                    {
                        Username = user.UserName,
                        NotificationOptions = allOptions,
                        NotificationLevel = allOptions.FirstOrDefault(x => x.Value == user.Notifications)
                    });

                }

В пользовательском интерфейсе я связываю itemsSource ComboBox с NotificationOptions с помощью конвертера. Поскольку эти NotificationOptions будут коллекцией ObservableCollection, у меня есть конвертер. Вот поле со списком,

<ComboBox Margin="{StaticResource MarginAfterText}" 
                                              x:Name="NotificationsComboBox" 
                                              Grid.Column="2"
                                              ItemsSource="{Binding AlertSettings.UserNotificationListWithAllRoles,Converter={StaticResource TestConverter}}" 
                                              SelectedValuePath="NotificationLevel"
                                              Width="200">

Вот мой конвертер,

public class TestConverter:IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            if(value is ObservableCollection<VmUserNotificationWithAllRoles> vmUserNotifications)
            {
                var item = vmUserNotifications.FirstOrDefault();
                if (item != null)
                {
                    return item.NotificationOptions;
                }
            }
            return null;
        }

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

Проблема в том, что поле со списком не выбирает значение, оно пустое. Пожалуйста помоги. Когда я сохраняю точку останова, я могу видеть значение для NotificationLevel.

1 Ответ

0 голосов
/ 07 марта 2020

SelectedValuePath работает только в сочетании с SelectedValue.

Если у вас есть, например, класс элементов типа

public class Item
{
    string Value { get; set; }
}

с моделью вида, например

public class ViewModel : INotifyPropertyChanged
{
    public ObservableCollection<Item> Items { get; } = new ObservableCollection<Item>();

    public string SelectedItemValue { get; set; } // must fire PropertyChanged
}

и ItemControl вроде

<ItemsControl ItemsSource="{Binding Items}"
              SelectedValue="{Binding SelectedItemValue}"
              SelectedValuePath="Value">
    ...
</ItemsControl>

, установив для свойства SelectedItemValue значение, например "Test", выберет элемент со свойством Value, установленным на "Test".

...