Search code examples
c#windows-8.1

Windows 8.1 Handle potentially different data types


I have a gridview which can fire a holding event on an item. The items consist of a stackpanel, textblock and an image which I am currently handling with the below code

private async void gvJobs_Holding(object sender, Windows.UI.Xaml.Input.HoldingRoutedEventArgs e)
{

            JobLocal job = null;
            if(e.OriginalSource is TextBlock)
            {
                job = (JobLocal)((TextBlock)e.OriginalSource).DataContext;
            }
            else if (e.OriginalSource is Image)
            {
                job = (JobLocal)((Image)e.OriginalSource).DataContext;
            }
            else if (e.OriginalSource is StackPanel)
            {
                job = (JobLocal)((StackPanel)e.OriginalSource).DataContext;
            }
            ....code based on above result
}

but i feel there is a better way than using multiple if statements. I tried using var but I then cannot access DataContext Could someone please advise on a better way to achieve my objective


Solution

  • Your UI Elements are derived from FrameworkElement so you can cast to this.

    if (e.OriginalSource is FrameworkElement) {
        job = (JobLocal)((FrameworkElement) e.OriginalSource).DataContext;
    }