Brannon
Brannon

Reputation: 5414

CollectionViewSource.View is null until the first valid source; empty View needed instead

My code looks like this:

var telemetry = new CollectionViewSource();
telemetry.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending));
SetTelemetryFilters(telemetry);

var binding = new Binding("Asset.TelemetryDefinitions.Values");
binding.Source = this;
var expression = BindingOperations.SetBinding(telemetry, CollectionViewSource.SourceProperty, binding);

Shortly after this code I am setting a ComboBox.ItemsSource = telemetry.View. I need view (in multiple places) because it implements IEnumerable and the CollectionViewSource does not. When the software first runs the Asset property is null. This is problematic because that causes telemetry.View to return null, which in turn means my ItemsSource was set to null. Is there some way to make the CollectionViewSource.View return an empty view in the case that the binding operation returns a null to CollectionViewSource.Source? (And I assume that once CollectionViewSource.View returns non-null it always returns the same instance?)

Upvotes: 1

Views: 1861

Answers (1)

hbarck
hbarck

Reputation: 2944

I think normally you'd use ItemsSource="{Binding Source={StaticResource myCollectionViewSource}}" instead of assigning the View directly to ItemsSource. This takes care of the CollectionViewSource.View changing from null to something... Is there a reason for your not setting this all up in XAML?

Upvotes: 1

Related Questions