How can I attach event handlers to items generated using databinding in WPF?
-
23-08-2019 - |
Question
I am developing for a MS Surface unit and am using a ScatterView
to display some data. The scenario below probably fits a normal ListBox
(and ListBoxItems
) too.
When I databind the ScatterView
, WPF automatically wraps the contents of the DataTemplate
with ScatterViewItems
. I want to attach some event handers for the ScatterManipulationCompleted
event of the (generated) ScatterViewItem
, but can't figure out how to do that.
Any help is much appreciated.
Solution
You can set a Style
on the container type and specify an EventSetter
like this:
<surface:ScatterView>
<surface:ScatterView.ItemContainerStyle>
<Style TargetType="{x:Type surface:ScatterViewItem}">
<EventSetter Event="ScatterManipulationCompleted" Handler="myHandler"/>
</Style>
</surface:ScatterView.ItemContainerStyle>
</surface:ScatterView>
OTHER TIPS
You should take advantage of routed events. You can just listen for this event at the ScatterView level.
<surface:ScatterView surface:ScatterViewItem.ScatterManipulationCompleted="OnManipulationCompleted"/>
As so often happens, I now found the/a answer. I've been looking at this for the last 20 hours or so, only to find it 5 minutes after posting the question :-(
Any way: the solution I found and which helps me for now is to use the Loaded event of the ScatterView. In the handler, I have the following loop:
for (int i = 0; i < MiniBrowserContent.Items.Count; i++)
{
ScatterViewItem svItem = (ScatterViewItem)(MiniBrowserContent.ItemContainerGenerator.ContainerFromIndex(i));
svItem.ScatterManipulationCompleted += new ScatterManipulationCompletedEventHandler(svItem_ScatterManipulationCompleted);
}
It all came to me after reading http://www.beacosta.com/blog/?p=7
Hope this helps anybody else.
Bye, Bart