aivanov
Topic Author
Posts: 19
Joined: 30 Sep 2024, 17:25

Sending RoutedEvent from Code Behind for Custom UserControl

10 Apr 2025, 16:56

Hello! I have a custom user control defined as `MyScreen` with the the following RoutedEvent `InitialFocus`. I am struggling to set up the EventTrigger in XAML to successfully catch this routed event. What might be going wrong? Is this behavior supported?
public partial class MyScreen: UserControl
{
    	public static readonly RoutedEvent InitialFocusEvent= EventManager.RegisterRoutedEvent(
            "InitialFocusEvent", RoutingStrategy.Direct, typeof(RoutedEventHandler), typeof(MyScreen));
        
        public event RoutedEventHandler InitialFocus
        {
            add => AddHandler(InitialFocusEvent, value);
            remove => RemoveHandler(InitialFocusEvent, value);
        }
}
Then in the xaml I have the following EventTrigger to listen for the routed event
<local:MyScreen>
    <b:Interaction.Triggers>
        <b:EventTrigger EventName="InitialFocus">
            <noesis:SetFocusAction Engage="False" TargetName="MyButton"/>
        </b:EventTrigger>
    </b:Interaction.Triggers>
</local:MyScreen>
When the RoutedEvent is triggered using the following line in the code behind it doesn't actually get caught by the EventTrigger in xaml and focus is not set:
RaiseEvent(new RoutedEventArgs(InitialFocusEvent, this));
 
User avatar
sfernandez
Site Admin
Posts: 3363
Joined: 22 Dec 2011, 19:20

Re: Sending RoutedEvent from Code Behind for Custom UserControl

10 Apr 2025, 20:27

I think the problem is in the name used to register the event:
public static readonly RoutedEvent InitialFocusEvent= EventManager.RegisterRoutedEvent(
            "InitialFocusEvent", RoutingStrategy.Direct, typeof(RoutedEventHandler), typeof(MyScreen));
Compared to when you hook to the event in the trigger:
<b:EventTrigger EventName="InitialFocus">
Could you try registering the event as "InitialFocus" instead?
 
aivanov
Topic Author
Posts: 19
Joined: 30 Sep 2024, 17:25

Re: Sending RoutedEvent from Code Behind for Custom UserControl

11 Apr 2025, 16:52

That was the issue! I was trying both ways but because of unrelated issues, noesis:SetFocusAction was not behaving as expected and I misidentified the problem.

Thank you!!

Who is online

Users browsing this forum: No registered users and 5 guests