Search code examples
c#wpfdata-bindingivalueconverter

ValueConverter not called on start up


I have combobox that is bound to a collection. Each item in the collection has a subcollection that might or might not contain items. I have a second combobox to which the subcollection is bound. And I only want to display (=Visibility.Visible) the second combobox if the subcollection has items. All that works. BUT: When I start my program, the selectedItem of the main combobox is null (=so far nothing has been selected). This (I guess) causes the converter to not be called (it doesn't, I have set a breakpoint on the converter and the program does not halt when it starts).

So I have the problem that I don't want to display the second combobox when the program starts. Can I force the ValueConverter to be called? I have tried invoking OnPropertyChanged at the end of the constructor, but that doesn't change anything. And when I set the combobox to Visible.Hidden in the constructor of the .xaml.cs, it will not show at all, even after the value converter is called. Any ideas?


Solution

  • Set a FallbackValue for the binding:

    <SomeUIElement Visibility="{Binding SomeBinding, Converter={StaticResource SomeConverter}, FallbackValue=Hidden}" />
    

    When there is nothing bound you can set a value that will be used in place of the binding.

    The reason changing the value in code-behind to Visibility.Hidden leaves it invisible all the time is because setting the property explicitly removes the binding that you have added in the XAML