Califf
Califf

Reputation: 505

Binding combobox selected value to an application setting

Having application properties mapped like this:

<Application.Resources>
    <properties:Settings x:Key="Settings" />
</Application.Resources>

The goal is to bind font size setting MainWindowFontSize (int) to a selected value on combobox:

<ComboBox 
  SelectedValuePath="Content"
  SelectedValue="{Binding Default.MainWindowFontSize, Source={StaticResource Settings}}">
<ComboBoxItem>8</ComboBoxItem>
...
<ComboBoxItem>48</ComboBoxItem>
</ComboBox>

The issue with this is that it works only in one direction, from the setting into ComboBox, but any selection in the combo is not going back to the setting. Everything seems to work fine when I use a regular property for font size in a model...

Any suggestions on how to make the binding to work with a setting both ways?

Upvotes: 1

Views: 1568

Answers (3)

Maksim Libenson
Maksim Libenson

Reputation: 58

It looks to be something new in .NET 4.5. I have found though that if you create binding in the code behind it works just fine. Like so:

    public MainWindow()
    {
        InitializeComponent();
        var binding = new Binding("Delay");
        binding.Source = Settings.Default;
        binding.Mode = BindingMode.TwoWay;
        BindingOperations.SetBinding(this.Combo, ComboBox.SelectedValueProperty, binding);
    }

Upvotes: 2

Califf
Califf

Reputation: 505

Found this workaround:

<ComboBox ...  SelectionChanged="MainWndFontSizeSelectionChanged" ...>

The event handler:

private void MainWndFontSizeSelectionChanged(object sender, SelectionChangedEventArgs e)
{
    var cb = (ComboBox)sender;
    int newSize = 0;
    if (Int32.TryParse(cb.SelectedValue.ToString(), out newSize) == true)
    {
        WpfApplication1.Properties.Settings.Default.MainWindowFontSize = newSize;
    }
}

Ugly, but works... Hoping for a better solution to come up...

This post provides more insight into the issue as it appears:LINK

It does not work the same way in .NET4.5 as in the previous versions.

Upvotes: 1

Arthur Nunes
Arthur Nunes

Reputation: 7058

Have you tried setting your binding's Mode to TwoWay?

<ComboBox 
  SelectedValuePath="Content"
  SelectedValue="{Binding Default.MainWindowFontSize, Source={StaticResource Settings}, Mode=TwoWay}">

You can try the UpdateSourceTrigger, also:

 <ComboBox 
  SelectedValuePath="Content"
  SelectedValue="{Binding Default.MainWindowFontSize, Source={StaticResource Settings}, Mode=TwoWay}, UpdateSourceTrigger=PropertyChanged">

Upvotes: 1

Related Questions