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}"> </DataTemplate> </UserControl.Resources>
c # wpf mvvm xaml
Ilian pinzon
source share