5

I have the following ComboBox:

<ComboBox SelectedItem="{Binding SelectedTheme, Mode=TwoWay}"
          ItemsSource="{Binding Themes, Mode=OneTime}" />

It is bound to the following values in my VM:

private Theme _selectedTheme;
public Theme SelectedTheme
{
    get { return _selectedTheme; }
    set
    {
        if (_selectedTheme != value)
        {
            _selectedTheme = value;
            OnPropertyChanged();
        }
    }
}

public List<Theme> Themes =>
    Enum.GetValues(typeof(Theme)).Cast<Theme>().ToList();

I set SelectedThemes value in the VM's ctor, and the get member is being hit after I assign the VM instance to my Page's DataContext. My trouble is the UI does not reflect the binding value the first time I load the page; it updates works correctly all other times, but the combobox does not show any selection after the page is initially loaded.

1 Answer 1

6

After struggling with this issue for about two hours, I realized that the UWP framework is connecting the bindings in the order they are set, so the SelectedItem is being set correctly, but is then cleared when the ItemsSource value is set. Changing my XAML to the following fixes the problem:

<ComboBox ItemsSource="{Binding Themes, Mode=OneTime}"
          SelectedItem="{Binding SelectedTheme, Mode=TwoWay}" />
Sign up to request clarification or add additional context in comments.

8 Comments

Besides that shouldnt you use observable collection instead of list? (interesting though never thought order of attributes would be important)
I don't need to because the list will never change.
So use OneTime binding Mode instead of TwoWay.
I typically don't set the mode if the default one works; is it important to? Also, isn't the default one-way?
Default mode varies on different properties. In your case its OneWay mode. But since your collection does not change and also can be made static, OneTime binding is lighter than other modes. So thats just optimizing hint.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.