0
设置的SelectedItem我有这势必状态列表的组合:无法在组合框从视图模型
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));
}
}
问题
- 该组合是空的视图模型时显示。
- 即使设置了绑定
Mode=TwoWay
,我也无法从视图模型中设置SelectedStatus
。
如何在启动时从视图模型中成功选择组合中的项目?
@ mm8是正确的。你不应该使用转换器选择项目。但是,它并不能解释为什么组合框是空的。它看起来像你绑定到错误的datacontext。在调试过程中检查输出窗口,是否存在一些绑定错误。还要确保ComboBox的DataContext被设置为ViewModel – Liero
注意,'Path = .'不会。它看起来不好。 – Will
@你完全正确,谢谢。 – openshac