无法通过ViewModel在ComboBox上设置SelectedItem

Openshac的

我有一个绑定到状态列表的组合:

public enum Status
{
    [Description(@"Ready")]
    Ready,

    [Description(@"Not Ready")]
    NotReady
}

我正在使用转换器在组合框中显示枚举的描述,该组合基于此处的示例:https : //stackoverflow.com/a/3987099/283787

public class EnumConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null)
        {
            return DependencyProperty.UnsetValue;
        }

        var description = GetDescription((Enum)value);

        return description;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var enumValue = GetValueFromDescription(value.ToString(), targetType);

        return enumValue;
    }
...

我绑定到视图中的combox框:

<ComboBox
    ItemsSource="{Binding Statuses}"
    SelectedItem="{Binding SelectedStatus, Converter={StaticResource EnumConverter}}">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Path=., Converter={StaticResource EnumConverter}}" />
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

我的视图模型包含以下内容:

public ObservableCollection<Status> Statuses { get; set; } = new ObservableCollection<Status>(new List<Status> { Status.Ready, Status.NotReady });

private Status selectedStatus = Status.Ready;
public Status SelectedStatus
{
    get
    {
        return this.selectedStatus;
    }

    set
    {
        this.selectedStatus = value;
        this.NotifyPropertyChanged(nameof(this.SelectedStatus));
    }
}

问题

  1. 视图模型显示时,该组合为空。
  2. SelectedStatus即使设置了binding,我也无法设置从视图模型Mode=TwoWay

如何在启动时从视图模型中成功选择组合中的项目?

毫米8

不要使用转换器进行SelectedItem绑定:

<ComboBox
    ItemsSource="{Binding Statuses}"
    SelectedItem="{Binding SelectedStatus}">
 ...

SelectedItem属性应绑定到Status源属性,前提是该ItemsSource属性绑定到ObservableCollection<Status>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章