Triggers with nested bindable collections - improved version

This is an improved version of solving nested collection's DataContext problem described in previous article.

A negative side of approach described in a previous article was that trigger's DataContext has to be initialized manually in XAML. But we can overcome this limitation by listening to the AssociatedObject context changes in trigger and reinitializing DataContext of nested collection with AssociatedObject's DataContext value:

        private static void OnDataContextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var ctrl = d as MessageBoxTrigger;
            if (ctrl != null)
            {
                ctrl.SetDataContext(e.NewValue);
            }
        }
 
        private void OnLoaded(object sender, RoutedEventArgs e)
        {
            SetDataContext(GetDataContext());
        }
 
        private void SetDataContext(object dataContext)
        {
            foreach (var item in MessageParameters)
            {
                item.DataContext = dataContext;
            }
        }

The updated version of trigger is in attachment.

AttachmentSize
triggerscollectionbindingdemo.zip124.37 KB