【问题标题】:DefaultValue for a ComboBox (set ONCE)组合框的默认值(设置一次)
【发布时间】:2012-01-12 21:17:31
【问题描述】:

我在 SO 和网络上阅读了很多内容,但没有找到答案... 我有一个绑定到 Collection 的 ComboBox,它是代码隐藏属性的一个属性,如下所示:

<ComboBox ItemsSource="{Binding Path=LocalizationUtil.AvailableLocales}"/>

这可行,但问题是当我的 UI 加载时,没有选择默认值,我想设置一个值,因为我知道我的 Collection 至少包含字符串“default”。 我看到了很多使用SelectedItemSelectedValue 的东西,但这会创建一种绑定,我希望它在开始时只启动一次。 我该怎么做?

【问题讨论】:

  • 这不适用于我的收藏:/
  • 您是否将 ComboBox 的 SelectedValue 绑定到任何东西?
  • 不,我这样做了,但我真的不喜欢它,因为 SelectedValue 然后被绑定了。我想要的是只执行一次的东西,什么时候加载 UI

标签: c# wpf xaml


【解决方案1】:

首先你必须创建一个像这样的枚举,这样你就可以在组合框上显示它:

[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);

希望对你有帮助。

【讨论】:

  • 如果您需要,我也可以发布我在 XAML 上的编写方式。
  • 我知道了,但这让我有点惊讶,因为你不能轻易地为 ComboBox 设置默认值,唯一的解决方案是定义这么多东西:o
  • 好的,我正在寻找一个“神奇”的 XAML 属性,所以我会坚持使用随机用户的解决方案!
【解决方案2】:
<ComboBox ItemsSource="{Binding Path=LocalizationUtil.AvailableLocales}" SelectedIndex="0"/>

【讨论】:

  • 我试过了,但我不能绝对确定“默认”字符串将是列表中的第一个:/ 实际上是,但我无法控制它在最后释放!
猜你喜欢
  • 2014-02-14
  • 1970-01-01
  • 2015-02-08
  • 2017-10-03
  • 2011-10-16
  • 1970-01-01
  • 2014-02-15
  • 2011-10-11
相关资源
最近更新 更多