2017-02-23 7 views
0

からのコンボボックスでのSelectedItemを設定できませんここでは一例に基づいて:https://stackoverflow.com/a/3987099/283787は、私はステータスのリストにバインドされたコンボを持っているViewModelに

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> 

マイビューモデルには、次のものが含まれていますとき、ビューモデルが表示さ

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

    問題は、コンボは空です。

  2. Mode=TwoWayを設定しても、ビューモデルからSelectedStatusを設定できません。

スタートアップ時のコンボとビューモデルからアイテムを選択するにはどうすればよいですか?

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

SelectedItemプロパティがItemsSourceプロパティがObservableCollection<Status>にバインドされていることを提供Statusソースプロパティにバインドする必要があります。

+0

@ mm8です。選択したアイテムにコンバータを使用しないでください。しかし、なぜコンボボックスが空であるのか説明していません。間違ったdatacontextにバインドしているようです。いくつかのバインディングエラーがあるかどうか、デバッグ中にウインドウを確認してください。また、コンボボックスのDataContextがViewModel – Liero

+0

サイドノートに設定されていることを確認してください。 'Path = .' plsはそうではありません。それは悪く見える。 – Will

+1

@ありがとうございます。ありがとうございます。 – openshac

答えて

1

は結合SelectedItemのためのコンバータを使用しないでください。