在C#Wpf中将枚举值列表绑定为ItemSource时,未更新选定的值

时间:2017-09-18 09:03:15

标签: c# wpf

我正在尝试将所选值绑定到字符串属性到组合框,其中itemsource与Enum值列表绑定。但是所选值不会显示在组合框中。

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 个答案:

答案 0 :(得分:1)

SelectedValue属性的类型必须与ItemsSource中的值类型相匹配。

FilterSelected属性的类型更改为FilterOperation,并将值设置为枚举值:

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

或者您必须使用值转换器在stringFilterOperationhttp://www.wpf-tutorial.com/data-binding/value-conversion-with-ivalueconverter/之间进行转换。 WPF不会自动为您完成此转换。