EDIT: See below for the solution I found.
I am trying to create a ComboBox in WPF/C# that pulls all available fonts from Fonts.SystemFontFamilies, and then selects the item based on a Setting.
The problem I'm running into is that the ItemsSource works, but binding the SelectedItem to settings is clearing the setting if Mode=TwoWay, or not selecting an item if Mode=OneWay.
Here's my XAML:
<ComboBox Name="customFontFace" SelectionChanged="customFontFace_SelectionChanged" ItemsSource="{Binding Source={x:Static Fonts.SystemFontFamilies}}" SelectedItem="{Binding Default.CustomFontFace, Source={StaticResource Settings}, Mode=TwoWay}" />
And a little bit of the code behind:
public Settings()
{
InitializeComponent();
customFontFace.SelectedItem = MyApplication.Properties.Settings.Default.CustomFontFace;
}
private void customFontFace_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// Doing nothing as of yet
}
In Settings.settings, the default for CustomFontFace is set to Consolas. If I add some logging output, I see that the setting shows Consolas, but then either gets blanked by the combobox or doesn't update the combobox, depending on the setting binding mode.
I've tried all the Modes and tried setting the SelectedItem in a few places, and I'm coming up empty. Any thoughts?
EDIT: Found my answer. By changing the type of CustomFontFace from string to System.Windows.Media.FontFamily, the binding works as expected. The default value of "Consolas" still works since there's a FontFamily(string source) constructor.
I still wasn't able to get it working perfectly in the code-behind, but this is a much simpler solution. For reference, if I used this in my code-behind, it worked, but only if the XAML had a binding for SelectedItem:
customFontFace.SelectedValue = Fonts.SystemFontFamilies.FirstOrDefault(x => x == MyApplication.Properties.Settings.Default.CustomFontFace);
Something happens when CustomFontFace is a string, and both the XAML binding and code-behind try to set SelectedValue, where the combobox value ends up blank. I haven't been able to log enough to see exactly what's happening.
customFontFace.SelectedItem = ...
? – dytori