2017-09-18 58 views
1

我試圖將所選值綁定到字符串屬性,以便將項目源綁定到枚舉值列表的組合框。但是,所選值不會顯示在組合框中。將Enum值列表綁定爲C#中的ItemSource時,未更新選定值Wpf

public enum FilterOperation 
{ 
    Includes, 
    NotIncludes, 
    Equals, 
    NotEquals   
} 

// Adding the Values to the list in constructor 
StringFilterList.Add(FilterOperation.Includes); 
StringFilterList.Add(FilterOperation.NotIncludes); 
StringFilterList.Add(FilterOperation.Equals); 
StringFilterList.Add(FilterOperation.NotEquals); 

// Initially assigning first value as default value. 
FilterSelected = StringFilterList.FirstOrDefault().ToString(); 


// XAML. 
<ComboBox HorizontalAlignment="Left"       
      ItemsSource="{Binding StringFilterList}" 
      SelectedValue="{Binding FilterSelected,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" 
      /> 

但是,即使列表已加載,所選值也未列出。

請嘗試解決此問題。

回答

1

SelectedValue屬性的類型必須與ItemsSource中值的類型匹配。

更改您的FilterSelected財產來FilterOperation類型和值設置爲枚舉值:

// Initially assigning first value as default value. 
FilterSelected = FilterOperation.Includes; 
//or: 
//FilterSelected = StringFilterList.FirstOrDefault(); 

或者你將不得不使用的值轉換器stringFilterOperation之間轉換:http://www.wpf-tutorial.com/data-binding/value-conversion-with-ivalueconverter/。 WPF不會爲你自動做這個轉換。