dotnet / wpf

WPF is a .NET Core UI framework for building Windows desktop applications.
MIT License
7.08k stars 1.17k forks source link

WPF ObservableCollection issue #2957

Closed richo-tri closed 4 years ago

richo-tri commented 4 years ago
weltkante commented 4 years ago

Visibility="{Binding MenuItems, ElementName=MyWindow, Converter={StaticResource EmptyListVisibilityConverter}}"

Why do you think the EmptyListVisibilityConverter should be called again? Thats not how WPF bindings work, you are binding against the list, the list does not get replaced, its still the same list.

Your converter code is accessing arbitrary properties off the C# objects, the binding engine can't know what properties you are depending on. What you instead want to do in this situation is create a MultiBinding with all dependencies and then use a converter which just combines the dependencies. Don't go collecting your dependencies manually in the converter code because then the binding engine doesn't know when you need to be updated.

Or rather, since you just have one dependency, you can do a direct binding against this dependency and run it through your converter, like you did in your other example that works.

Visibility="{Binding MenuItems.Count, ElementName=MyWindow, Converter={StaticResource ListCountVisibilityConverter}}"

Thats the correct way to do it, the binding engine now knows it has to notify the converter when Count changes.

richo-tri commented 4 years ago

I assumed that the observable collection would work similar to how it does when bound to the ItemsControl. The ItemsControl updates just fine.

weltkante commented 4 years ago

The ItemsControl manually subscribes itself to its ItemsSource, it doesn't get updated by the binding engine either. You could do the same in your converter, but its not going to happen automatically. How should the binding system know that your converter is accessing random properties on the object instead of just checking it for null and calculating the visibility from that? (If you try to subscribe yourself inside the converter you'll have a hard time getting the converter reevaluated though, thats not how the system is designed, better just tell the binding engine your dependencies and let it do its job.)

kronic commented 4 years ago

Binding to count property

richo-tri commented 4 years ago

Ok thanks for explaining.