C# – How to add an Event Trigger to a data template for a business object

cdatatemplateeventseventtriggerwpf

I have a custom class named BlinkingLight.
I also have a static ObservableCollection BlinkingLightCollection.
In the UI, I have a ListBox that is bound to BlinkingLightCollection.

In my ListBox I want to essentially display each BlinkingLight object as a custom control that looks like box with an LED light that has an animation that makes the LED look like it just flashed on for a second then goes back to normal.

My BlinkingLight class has third party "LED" object that raises an event called 'Flash'.

I am looking for ideas or solutions to get this to work!

My failed attempt:

I created a custom control (BlinkingLightControl) that can bind to the data of my BlinkingLight class when a BlinkingLight is the DataContext of my custom control.

I created a DataTemplate for my ListBox:

<Window.Resources>
  <DataTemplate x:Key="blinkingLightItemTemplate" >
    <local:BlinkingLightControl />
  </DataTemplate>
</Window.Resources>

<ListBox ItemsSource={Binding Source={x:Static local:Data.BlinkingLightCollection}}
         ItemTemplate="{StaticResource blinkingLightItemTemplate}" />

Note: I can just put the xaml for my custom control into the datatemplate instead having a completely different control if that makes things easier.

Now I want to have an EventTrigger in my BlinkingLightControl (or DataTemplate) who's RoutedEvent is the LED.Flash event. Unfortunately I can't seem to figure this part out. I've tried to create a RoutedEvent in my BlinkingLight class and just raise it whenever I handle the LED.Flash event. However my class is not a UIElement or ContentElement, and per MSDN: MSND Link

"The routed event owner can be any class, but routed events must be raised by and handled by UIElement or ContentElement derived classes in order to be useful. For more information about custom events, see How to: Create a Custom Routed Event."

Any help would be greatly appreciated!!
Thanks,
Scott

Best Answer

In this case, the best way is to use WPF Commanding and create a "BlinkTheLights" RoutedCommand - your BlinkingLightControl will handle the BlinkTheLights command, and respond by starting a StoryBoard which does the light blink.

Related Topic