WPF: Binding to ObservableCollection in ControlTemplate is not updated

徘徊边缘 提交于 2019-12-11 06:06:58

问题


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.


回答1:


The problem is that your Children property itself never changes, just its content. Since the property value doesn't change, the binding isn't reevaluated. What you need to do is bind to the Count property of the collection. The easiest way you can achieve this is with a DataTrigger in your template:

<ControlTemplate TargetType="{x:Type MyControl}">
  <!-- ... other stuff that works ... -->
  <!-- Child components -->
  <GroupBox x:Name="gb" Header="Children">
    <ItemsControl ItemsSource="{TemplateBinding Children}"/>
  </GroupBox>
  <ControlTemplate.Triggers>
      <DataTrigger Binding="{Binding Path=Children.Count, RelativeSource={RelativeSource TemplatedParent}}"
                   Value="0">
        <Setter TargetName="gb" Property="Visibility" Value="Collapsed" />
      </DataTrigger>
  </ControlTemplate.Triggers>
</ControlTemplate>



回答2:


You need to notify whenever the number of items in your Children property changes. You can do that by implementing INotifyPropertyChanged interface, register to Children collection's CollectionChanged event and raise PropertyChanged from there.

Example:

public class MyControl : Control, INotifyPropertyChanged
{
    static MyControl()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(MyControl), new FrameworkPropertyMetadata(typeof(MyControl)));
    }

    public ObservableCollection<UIElement> Children
    {
        get { return (ObservableCollection<UIElement>)GetValue(ChildrenProperty); }
        set { SetValue(ChildrenProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Children.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty ChildrenProperty =
        DependencyProperty.Register("Children", typeof(ObservableCollection<UIElement>), typeof(MyControl), new UIPropertyMetadata(0));

    public MyControl()
    {
        Children = new ObservableCollection<UIElement>();
        Children.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(Children_CollectionChanged);
    }

    void Children_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {
        RaisePropertyChanged("Children");
    }

    public event PropertyChangedEventHandler PropertyChanged;
    public void RaisePropertyChanged(String propertyName)
    {
        PropertyChangedEventHandler temp = PropertyChanged;
        if (temp != null)
        {
            temp(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}


来源:https://stackoverflow.com/questions/3046262/wpf-binding-to-observablecollection-in-controltemplate-is-not-updated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!