WPF: Binding to ObservableCollection in ControlTemplate is not updated
Posted
by Julian Lettner
on Stack Overflow
See other posts from Stack Overflow
or by Julian Lettner
Published on 2010-06-15T14:45:23Z
Indexed on
2010/06/15
15:52 UTC
Read the original article
Hit count: 542
I created a ControlTemplate
for my custom control MyControl
.
MyControl
derives from System.Windows.Controls.Control
and defines the following property public ObservableCollection<MyControl> Children{ get; protected set; }
.
To display the nested child controls I am using an ItemsControl
(StackPanel
) which is surrounded by a GroupBox
. If there are no child controls, I want to hide the GroupBox
.
Everything works fine on application startup: The group box and child controls are shown if the Children property initially contained at least one element. In the other case it is hidden.
The problem starts when the user adds a child control to an empty collection. The GroupBox
's visibility is still collapsed. The same problem occurs when the last child control is removed from the collection. The GroupBox
is still visible.
Another symptom is that the HideEmptyEnumerationConverter
converter does not get called.
Adding/removing child controls to non empty collections works as expected.
Whats wrong with the following binding? Obviously it works once but does not get updated, although the collection I am binding to is of type ObservableCollection
.
<!-- Converter for hiding empty enumerations -->
<Common:HideEmptyEnumerationConverter x:Key="hideEmptyEnumerationConverter"/>
<!--- ... --->
<ControlTemplate TargetType="{x:Type MyControl}">
<!-- ... other stuff that works ... -->
<!-- Child components -->
<GroupBox Header="Children"
Visibility="{Binding RelativeSource={RelativeSource TemplatedParent},
Path=Children, Converter={StaticResource hideEmptyEnumerationConverter}}">
<ItemsControl ItemsSource="{TemplateBinding Children}"/>
</GroupBox>
</ControlTemplate>
.
[ValueConversion(typeof (IEnumerable), typeof (Visibility))]
public class HideEmptyEnumerationConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
int itemCount = ((IEnumerable) value).Cast<object>().Count();
return itemCount == 0 ? Visibility.Collapsed : Visibility.Visible;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
Another, more general question: How do you guys debug bindings? Found this (http://bea.stollnitz.com/blog/?p=52) but still I find it very hard to do.
I am glad for any help or suggestion.
© Stack Overflow or respective owner