Is there a way to consolidate similar data bindings and / or triggers in XAML?

I have a user control that hosts other controls. The way I implemented this is to use data templates that define the control that needs to be associated with a particular view model. These view models have similar properties and interaction triggers. See the XAML snippet below.

The problem with this approach is that I would have to copy the data binding attachments if I want to support the new view model. Is there a way to combine all similar data bindings and / or triggers into one template? I do not want to type / copy-paste the same data binding definitions into each control. (Yes, I know, I'm lazy.)

<UserControl.Resources> <DataTemplate DataType="{x:Type vm:SomeViewModel1}"> <TextBlock Canvas.Left="{Binding Left}" Canvas.Top="{Binding Top}" RenderTransform="{Binding Transform}" Height="{Binding Height}" Width="{Binding Width}"> <i:Interaction.Triggers> <i:EventTrigger EventName="MouseEnter"> <cmd:EventToCommand Command="{Binding MouseEnterCommand}"/> </i:EventTrigger> <i:EventTrigger EventName="MouseLeave"> <cmd:EventToCommand Command="{Binding MouseLeaveCommand}"/> </i:EventTrigger> </i:Interaction.Triggers> </TextBlock> </DataTemplate> <DataTemplate DataType="{x:Type vm:SomeViewModel2}"> <Rectangle Canvas.Left="{Binding Left}" Canvas.Top="{Binding Top}" RenderTransform="{Binding Transform}" Height="{Binding Height}" Width="{Binding Width}"> <i:Interaction.Triggers> <i:EventTrigger EventName="MouseEnter"> <cmd:EventToCommand Command="{Binding MouseEnterCommand}"/> </i:EventTrigger> <i:EventTrigger EventName="MouseLeave"> <cmd:EventToCommand Command="{Binding MouseLeaveCommand}"/> </i:EventTrigger> </i:Interaction.Triggers> </Rectangle> </DataTemplate> <DataTemplate DataType="{x:Type vm:SomeViewModel3}"> <Button Canvas.Left="{Binding Left}" Canvas.Top="{Binding Top}" RenderTransform="{Binding Transform}" Height="{Binding Height}" Width="{Binding Width}"> <i:Interaction.Triggers> <i:EventTrigger EventName="MouseEnter"> <cmd:EventToCommand Command="{Binding MouseEnterCommand}"/> </i:EventTrigger> <i:EventTrigger EventName="MouseLeave"> <cmd:EventToCommand Command="{Binding MouseLeaveCommand}"/> </i:EventTrigger> </i:Interaction.Triggers> </Button> </DataTemplate> <DataTemplate DataType="{x:Type vm:SomeViewModel4}"> <!-- Do not want copy-paste code here... --> </DataTemplate> </UserControl.Resources> 
+7
c # wpf mvvm xaml
source share
2 answers

You can use a generic style and put both your properties and triggers (which are also properties) inside this style, look at this https://stackoverflow.com/a/1662695/ ... for more details.

+1
source share

How to include triggers in a resource and associate them with your controls. Or use your own base class for your DataTemplates.

0
source share

All Articles