Search code examples
c#wpfrouted-eventsroutedeventargs

How to compare xaml page versus e.OriginalSource?


I have a method that looks like below:

private void someEvent(RoutedEventArgs e)
{
    if(e.OriginalSource == typeof(a.b.c.somePages))
}

This method will be in my viewModel. From breakpoint, I can see there is this e.OriginalSource which has my xaml page somePages as value. Hence I'm trying to compare the value. But it's giving me warning as below:

Possible unintended reference comparison; to get a value comparison, 
cast the left hand side to type 'System.Type'

So I updated my code to if((System.Type)e.OriginalSource == typeof(a.b.c.somePages)) but the warning is still there. May I know what's wrong?


Solution

  • In this situation, you need to type cast. You can not get the type of an object without a cast because for e.OriginalSource type will be Object. Besides, in the construction typeof is to be an object of System.Type type:

    Used to obtain the System.Type object for a type.

    Therefore try this:

    Page page = e.OriginalSource as Page;
    
    if (page != null) 
    {
        string test = page.ToString();
    }
    

    Or just use ToString() method for e.OriginalSource like you mentioned.