Triggers with nested bindable collections

Although triggers in Silverlight 4 are bindable, it seems that there are problems with binding of its nested collections, as it was noticed also on a thread on Silverlight.net forums. However, collection binding may be useful when you want to create a functionality with infinite number of parameters defined in XAML. Here we discuss possible methods to overcome this limitation.

For example, let's suppose we wanted to create a MessageBoxAction taking a format string with an infinite number of bindable parameters defined in XAML, so it'll look like:

            <i:Interaction.Triggers>
                <i:EventTrigger EventName="Click">
                    <local:MessageBoxTrigger Message="1: {0}; 2: {1}; 3: {2};">
                        <local:MessageBoxTrigger.MessageParameters>
                            <local:ParameterItem Value="{Binding Parameter1}"/>
                            <local:ParameterItem Value="{Binding Parameter2}"/>
                            <local:ParameterItem Value="{Binding Parameter3}"/>
                        </local:MessageBoxTrigger.MessageParameters>
                    </local:MessageBoxTrigger>
                </i:EventTrigger>
            </i:Interaction.Triggers>

Unfortunately, binding just don't work here, maybe because TriggerAction is inherited from DependencyObject which doesn't have its own DataContext. Possible ways to overcome this problem:

1. Define inside MessageBoxTrigger its own DataContext dependency property, then initialize it in XAML by adding DataContext="{Binding}" to MessageBoxTrigger properties, so it'll look like:

<local:MessageBoxTrigger DataContext="{Binding}" Message="1: {0}; 2: {1}; 3: {2};">

Binding in ParameterItems will work, as you can see in the attached project. However this is not a perfect way to fix the problem: it'll require to write DataContext="{Binding}" every time you use MessageBoxTrigger, and ElementName binding in parameters won't work in this case.
UPDATE: this is no longer needed, see an improved version of this article and sources.

2. Define parameters in non-visual user control, then reference it in trigger through ElementName binding.

AttachmentSize
triggerscollectionbindingdemo.zip122.04 KB

Comments

Thanks for the trigger

I like it:)