2017-02-23 34 views
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)); 
    } 
} 

問題

  1. 該組合是空的視圖模型時顯示。
  2. 即使設置了綁定Mode=TwoWay,我也無法從視圖模型中設置SelectedStatus

如何在啓動時從視圖模型中成功選擇組合中的項目?

+0

@ mm8是正確的。你不應該使用轉換器選擇項目。但是,它並不能解釋爲什麼組合框是空的。它看起來像你綁定到錯誤的datacontext。在調試過程中檢查輸出窗口,是否存在一些綁定錯誤。還要確保ComboBox的DataContext被設置爲ViewModel – Liero

+0

注意,'Path = .'不會。它看起來不好。 – Will

+1

@你完全正確,謝謝。 – openshac

回答

1

不要使用該SelectedItem綁定一個轉換器:

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

SelectedItem屬性應綁定到提供的ItemsSource屬性綁定到一個ObservableCollection<Status>一個Status源屬性。