Page 1 of 1

Sending RoutedEvent from Code Behind for Custom UserControl

Posted: 10 Apr 2025, 16:56
by aivanov
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));

Re: Sending RoutedEvent from Code Behind for Custom UserControl

Posted: 10 Apr 2025, 20:27
by sfernandez
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?

Re: Sending RoutedEvent from Code Behind for Custom UserControl

Posted: 11 Apr 2025, 16:52
by aivanov
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!!