WPF Binding My.Settings collection to Combobox items

前端 未结 5 1952
长情又很酷
长情又很酷 2021-02-15 16:18

I\'m VERY new to WPF, and still trying to wrap my head around binding in XAML.

I\'d like to populate a combobox with the values of a string collection in my.settings. I

5条回答
  •  自闭症患者
    2021-02-15 16:46

    You could also store the list as a delimited string in settings then use a converter.

    
    /// 
    /// Converts a delimited set of strings to a list and back again. The parameter defines the delimiter
    /// 
    public class StringToListConverter : IValueConverter {
     /// 
     /// Takes a string, returns a list seperated by {parameter}
     /// 
     public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
         string serializedList = (value ?? string.Empty).ToString(),
                splitter = (parameter ?? string.Empty).ToString();
         if(serializedList.Trim().Length == 0) {
             return value;
         }
         return serializedList.Split(new[] { splitter }, StringSplitOptions.RemoveEmptyEntries);
     }
     /// 
     /// Takes a list, returns a string seperated by {parameter}
     /// 
     public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
         var items = value as IEnumerable;
         var splitter = (parameter ?? string.Empty).ToString();
         if(value == null || items == null) {
             return value;
         }
         StringBuilder buffer = new StringBuilder();
         foreach(var itm in items) {
             buffer.Append(itm.ToString()).Append(splitter);
         }
         return buffer.ToString(0, splitter.Length > 0 ? buffer.Length - splitter.Length : buffer.Length);
     }
    }
    

    Then when a browse button is clicked, you can add to the list:

    var items = Settings.Default.ImportHistory.Split('|');
    if(!items.Contains(dlgOpen.FileNames[0])) {
     Settings.Default.ImportHistory += ("|" + dlgOpen.FileNames[0]);
    }
    cboFilename.SelectedValue = dlgOpen.FileNames[0];
    Settings.Default.Save();
    

提交回复
热议问题