I have a ObservationCollection in my CustomControl's class.
public static readonly DependencyProperty ItemsProperty = DependencyProperty.Register("Items", typeof(ObservableCollection<Draggable>), typeof(Draggable), new PropertyMetadata(new ObservableCollection<Draggable>(), OnItemsChanged));
private static void OnItemsChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
Draggable draggable = (Draggable)obj;
if (e.NewValue != null)
{
if (((ObservableCollection<Draggable>)e.NewValue).Count > 0)
draggable.HasItem = true;
else
draggable.HasItem = false;
}
else
{
draggable.Items = new ObservableCollection<Draggable>();
draggable.HasItem = false;
}
}
and By default it has assigned by a new ObservableCollection<Draggable>
.
I cant keep track of adding or removing the Items to/from this collection.
OnItemsChanged
will fires whenever i assign a new ObservableCollection to this property. so Adding or removing the Items will not raise anything for me.
I have another property called HasItem
. In my ControlTemplate i will show a Grid Whenever this property is True but it will never be True.
How can i solve this problem ?
EDIT:
My Main Class is Draggable
and the ObservableCollection is the same in type.
I have tried two solution:
I have written a ValueConverter:
[ValueConversion(typeof(ObservableCollection), typeof(Visibility))] public class IntToVisibilityConverter : IValueConverter { public static IntToVisibilityConverter Instance = new IntToVisibilityConverter();
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { ObservableCollection<Draggable> Source = (ObservableCollection<Draggable>)value; if (Source.Count > 0) return Visibility.Visible; else return Visibility.Collapsed; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); }
}
and i used it in this way:
<Border x:Name="ItemsContainer" Visibility="{Binding Path=Items,Converter={x:Static MyConverters:IntToVisibilityConverter.Instance}}" ... >
And I have written a constructor for my class and I added CollectionChanged event:
public Draggable() { Items.CollectionChanged += Items_CollectionChanged; } private void Items_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { if (Items.Count > 0) HasItem = true; else HasItem = false; }
both of them will throw in an Infinite Loop As VisualStudio Says. I can't Understand this because I cant see the loop it says.