I have a dependency property of type collection, when its callback fires based on the count I need to set the visibility of some of the controls on the screen.
But the controls remains Collapsed all the time.
As per the code, one control remains visible all the time.
XAML binding is
<TextBlock Text="106 search results for 'a'" Margin="5,0,100,0" Visibility="{Binding CountLabelVisibleReverse, Converter={StaticResource VisibilityConverter}}"/>
<StackPanel Grid.Row="1" Orientation="Horizontal" Margin="0,0,90,0"
Visibility="{Binding CountLabelVisible, Converter={StaticResource VisibilityConverter}}">
<TextBlock Text="Sort By" />
<ComboBox Style="{StaticResource ComboBoxStyle1}" Width="100" x:Name="ComboBoxSorting" ItemsSource="{Binding SortBy}" />
</StackPanel>
My two properties are
public bool CountLabelVisible { get; set; }
public bool CountLabelVisibleReverse { get; set; }
Dependency property callback
private static void ItemsCollectionChanged(DependencyObject obj, DependencyPropertyChangedEventArgs eventArgs)
{
var listingUserControl = (obj as ListingUserControl);
var itemsResult = (eventArgs.NewValue as List<ItemsResult>);
if (listingUserControl != null && itemsResult != null)
{
listingUserControl.CountLabelVisible = itemsResult.Count > 0;
listingUserControl.CountLabelVisibleReverse =itemsResult.Count <= 0;
}
}
Converter code is
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (parameter == null)
return (bool)value == false ? Visibility.Collapsed : Visibility.Visible;
return (bool)value ? Visibility.Collapsed : Visibility.Visible;
}
You have made the classic mistake of binding to auto properties that are valid for binding, but don’t notify upon change, which means the binding subsystem cannot detect changes and update the binding targets.
To fix this, implement INotifyPropertyChanged on your viewmodel, and then ensure that you notify the property change from the properties.
As an example, I have the following in the base class for my viewmodels:
then in your regular viewmodel:
This way, when
CountLabelVisiblegets changed it also notifies on the propertyCountLabelVisibleReverse, and the propertyCountLabelVisibleReverseconsists of only a getter – because it will always be the inverse ofCountLabelVisible.So that fixes your code the way you have it, but the reality is you don’t need to keep the
CountLabelVisibleReverseproperty, instead you could: