Search code examples
c#wpffontscomboboxbinding

Binding Application Setting to ComboBox , comboBox shows empty on load


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

Solution

  • 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.