我有一个绑定到状态列表的组合:
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));
}
}
问题
SelectedStatus
即使设置了binding,我也无法设置从视图模型Mode=TwoWay
。如何在启动时从视图模型中成功选择组合中的项目?
不要使用转换器进行SelectedItem
绑定:
<ComboBox
ItemsSource="{Binding Statuses}"
SelectedItem="{Binding SelectedStatus}">
...
该SelectedItem
属性应绑定到Status
源属性,前提是该ItemsSource
属性绑定到ObservableCollection<Status>
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句