【发布时间】:2020-03-06 22:55:28
【问题描述】:
我有一个类如下,
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 中,我有一个 VmUserNotificationWithAllRoles 的 ObservableCollection。我将其填充如下,
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)
});
}
在 UI 中,我使用转换器将 ComboBox 的 itemsSource 绑定到 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();
}
}
问题是 Combobox 没有选择值,它是空白的。请帮忙。当我保留断点时,我可以看到 NotificationLevel 的值。
【问题讨论】:
标签: c# wpf xaml data-binding