Silverlight: Can I include interaction triggers in resources for reuse?

I have a bunch of controls that use the same interaction triggers between multiple user controls and view modes. Can I somehow put these triggers in a resource dictionary for reuse? Here is an example of how a control might look.

<TextBox x:Name="FirstName" Grid.Row="1" Grid.Column="1"> <i:Interaction.Triggers> <i:EventTrigger EventName="KeyDown"> <cal:ActionMessage MethodName="KeyPressed" /> </i:EventTrigger> </i:Interaction.Triggers> </TextBox> <TextBox x:Name="Initial" Grid.Row="1" Grid.Column="1"> <i:Interaction.Triggers> <i:EventTrigger EventName="KeyDown"> <cal:ActionMessage MethodName="KeyPressed" /> </i:EventTrigger> </i:Interaction.Triggers> </TextBox> <TextBox x:Name="LastName" Grid.Row="1" Grid.Column="1"> <i:Interaction.Triggers> <i:EventTrigger EventName="KeyDown"> <cal:ActionMessage MethodName="KeyPressed" /> </i:EventTrigger> </i:Interaction.Triggers> </TextBox> 

The cal: namespace refers to the Caliburn.Micro MVVM structure and is probably not relevant to this issue.

+4
source share
2 answers

It is not possible to reuse a single instance of Interaction.Triggers in a resource because it is attached to the control. This attachment becomes part of its state, so a single instance cannot be used by multiple controls.

You will need to include Interaction.Triggers in the template to create multiple instances. I think something like the following might work (warning air code).

 <UserControl.Resources> <DataTemplate x:key="MyTextBox"> <TextBox> <i:Interaction.Triggers> <i:EventTrigger EventName="KeyDown"> <cal:ActionMessage MethodName="KeyPressed" /> </i:EventTrigger> </i:Interaction.Triggers> </TextBox> </DataTemplate> </UserControl.Resources> 

...

 <ContentPresenter x:Name="FirstName" Grid.Row="1" Grid.Column="1" ContentTemplate="{StaticResource MyTextBox}" /> <ContentPresenter x:Name="Initial" Grid.Row="1" Grid.Column="1" ContentTemplate="{StaticResource MyTextBox}" /> <ContentPresenter x:Name="LastName" Grid.Row="1" Grid.Column="1" ContentTemplate="{StaticResource MyTextBox}" /> 

It is my opinion that this kind of thing is not worth it. Triggers interaction stuff is really aimed at empowering the designer, not the developer. The designer is not worried that there is repetition in the "code".

+3
source

I have something useful if you don’t have a complete solution to the problem of reusing interaction triggers ...

 <TextBox x:Name="FirstName" KeyDown="_KeyDown"> 

...

 private void TextBlock_KeyDown(object sender, System.Windows.Input.KeyEventArgs e) { Here goes something you wanna reuse for all your TextBox controls.. } 

Perhaps the best option is to use a design pattern such as MVVM and EventToCommand Interactions by GalaSoft

+1
source

Source: https://habr.com/ru/post/1332969/


All Articles