组合框的默认值(设置ONCE)
问题描述:
我在这里阅读了很多关于SO和网页的东西,但没有找到答案... 我得到了一个绑定到集合的ComboBox,它是一个代码的属性-behind财产,像这样:组合框的默认值(设置ONCE)
<ComboBox ItemsSource="{Binding Path=LocalizationUtil.AvailableLocales}"/>
这工作,但事情是,加载我的用户界面时,没有默认值被选中,我想设置一个值,因为我知道我的收藏包含至少字符串“默认”。 我看到很多东西使用SelectedItem
或SelectedValue
但这创建了一种绑定,我希望它只在一开始就启动。 我该怎么做?
答
首先,你必须创建这样一个枚举,这样你就可以显示它在组合框:
[Flags]
public enum Actions
{
[Description("None")]
None = 0,
[Description("Edit")]
Edit = 1,
[Description("Print")]
Imprimir = 2,
}
此之后,你必须创建一个方法到一个IEnumerable返回到您的财产,像这样:
/// <summary>
/// Get the list with names and descriptions of Enum
/// </summary>
/// <typeparam name="T">Enum Type</typeparam>
/// <param name="usarNome">if true the key is the Enum name</param>
/// <returns>List with names and descriptions</returns>
public static IEnumerable<KeyValuePair<string, T>> GetEnumList<T>(bool usarNome)
{
var x = typeof(T).GetFields().Where(info => info.FieldType.Equals(typeof(T)));
return from field in x
select new KeyValuePair<string, T>(GetEnumDescription(field, usarNome), (T)Enum.Parse(typeof(T), field.Name, false));
}
然后你在构造函数中定义它或任何你想要的:
MyActions = EnumHelpers.GetEnumList<Actions>(false);
希望它可以帮助你。
答
<ComboBox ItemsSource="{Binding Path=LocalizationUtil.AvailableLocales}" SelectedIndex="0"/>
+0
我试过了,但我不能绝对确定“默认”字符串将成为列表中的第一个:/实际上它是,但我赢了'在最终版本中,你无法控制它! – 2012-01-12 13:10:16
[显示数据绑定WPF组合框的默认值]的可能重复(http://stackoverflow.com/questions/1910896/display-a-default-value-for-a-databound-wpf-combobox) – stuartd 2012-01-12 13:02:45
This不适用于我拥有的集合:/ – 2012-01-12 13:04:55
您是否将您的ComboBox的SelectedValue绑定到任何东西? – 2012-01-12 13:08:58