2

I read a lot of things here on SO and on the web but didnt find an answer... I got a ComboBox that is binded to a Collection which is a property of a code-behind property, like this :

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

This works but the thing is that when my UI is loaded, no default value is selected and I'd like to set a value 'cause I KNOW that my Collection contains at least the string "default". I saw a lot of things using SelectedItem or SelectedValue but this create a sort of Binding and I want it to be initiated only ONCE, at start. How can I do that ?

Guillaume Slashy
  • 3,554
  • 8
  • 43
  • 68
  • possible duplicate of [Display a Default value for a Databound WPF ComboBox](http://stackoverflow.com/questions/1910896/display-a-default-value-for-a-databound-wpf-combobox) – stuartd Jan 12 '12 at 13:02
  • This is not applyable to the Collection I have :/ – Guillaume Slashy Jan 12 '12 at 13:04
  • Do you bind your ComboBox's SelectedValue to anything at all? –  Jan 12 '12 at 13:08
  • No, I did this but I really don't like it because the SelectedValue is then bound. What I want is something executed only once, when is the UI is loaded – Guillaume Slashy Jan 12 '12 at 13:12

2 Answers2

2
<ComboBox ItemsSource="{Binding Path=LocalizationUtil.AvailableLocales}" SelectedIndex="0"/>
  • I tried it but I can't be absolutely sure that the "default" string will be the first in the List :/ Actually it is, but I won't have control on it in the final release ! – Guillaume Slashy Jan 12 '12 at 13:10
2

First you have to create an enum like this one, so you'll be able to show it on combobox :

[Flags]    
public enum Actions
{
    [Description("None")]
    None = 0,
    [Description("Edit")]
    Edit = 1,
    [Description("Print")]
    Imprimir = 2,
}

After this you must create a method to return an IEnumerable to your property, like this :

    /// <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));    
    }   

And then you define it in your constructor or wherever you want:

    MyActions = EnumHelpers.GetEnumList<Actions>(false);

Hope it helps you.

Vinicius
  • 541
  • 3
  • 15