Home > Mobile >  Binding Application Setting to ComboBox , comboBox shows empty on load
Binding Application Setting to ComboBox , comboBox shows empty on load

Time:09-23

I am design a setting window to control font family for text of my WPF application. I used Application Setting in order to read , write and save user settings. every thing works fine . selected font is saved correctly and font will be changed right on selection from a ComboBox . The only problem is each time I open Font Setting Windows , ComboBoxes are not showing current selected Font and user wont be able to find out what font is being used now

as you can see in the image no font is shown in combobox , however correct font is being used

no font is shown in combobox

but after selecting font from combobox . font will be changed correctly and will be displayed in the combobox. save and close the window then opening it again will keep the correct font but the combobox will be empty once more .

selecting fonts works fine

here is the code :

<ComboBox Grid.Row="1" Grid.Column="0" Name="TextFont"
          SelectedValue="{Binding
                          Path=(p:Settings.Default).TextFontFamily,
                          Mode=TwoWay}" />

combobox Itemsource is set in C# code

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        FontList = Fonts.SystemFontFamilies.ToList();
        TextFont.ItemsSource = FontList;
    }

CodePudding user response:

If you do not set a value for the SelectedValuePath property, then the SelectedValue property will have the same value as the SelectedItem property. That is, there will be an instance of FontFamily. And at you in settings the line is stored. By default, there is no way to compare the string to the FontFamily, so the WPF logic assumes that the element initially selected is not in the "SystemFontFamilies" collection.

Try to use this code:

<ComboBox Grid.Row="1" Grid.Column="0" Name="TextFont"
          SelectedValuePath="Source"
          SelectedValue="{Binding
                          Path=TextFontFamily,
                          Source={x:Static p:Settings.Default},
                          Mode=TwoWay}"/>

This code will write and restore the selected FontFamily value from its FontFamily.Source property.

CodePudding user response:

The FontList and TextFontFamily must be of same type (ex. string) and TextFontFamily must be one of the items in the FontList..

So if FontList = (A, B, C), and TextFontFamily = D, the selected value won't show up.. there must be 'D' in FontList collection (i.e. FontList = (A, B, C, D), this way it will work).

  • Related