【问题标题】:Cannot set SelectedItem on ComboBox from ViewModel无法从 ViewModel 在 ComboBox 上设置 SelectedItem
【发布时间】:2017-02-23 11:22:02
【问题描述】:

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

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;
    }
...

我正在绑定到视图中的组合框:

<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,即使我设置了绑定Mode=TwoWay

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

【问题讨论】:

  • @mm8 是对的。你不应该对选定的项目使用转换器。但是,它没有解释为什么组合框是空的。看起来您绑定到错误的数据上下文。在调试过程中检查你的输出窗口,是否有一些绑定错误。还要确保 ComboBox 的 DataContext 设置为 ViewModel
  • 旁注,Path=. 请不要。看起来很糟糕。
  • @你说得对吗,谢谢。

标签: wpf mvvm combobox ivalueconverter


【解决方案1】:

不要为SelectedItem 绑定使用转换器:

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

SelectedItem 属性应绑定到 Status 源属性,前提是 ItemsSource 属性绑定到 ObservableCollection&lt;Status&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 2011-03-27
    • 1970-01-01
    • 2017-08-06
    • 2011-02-23
    相关资源
    最近更新 更多