Search code examples
c#tuplesselecteditemchanged

SelectedItemChanged Event bind to an ObservableCollection<Tuple<string, object>>


Here is the ObservableCOllection that it the "ItemSource" of my TreeView :

ObservableCollection<Tuple<string, object>>

The thing is that I am now writing the SelectedItemChanged Event and I got the following problem. AS far as I tried, I CAN NOT get anything else than it for my function declaration :

private void plugin_Selected(object sender, RoutedPropertyChangedEventArgs<object> e)

(and I got the following code in xaml :

SelectedItemChanged="plugin_Selected"

)

The thing is that when I do

e.NewValue.GetType()

of course I got a Tuple<string, object> but in my plugin_Selected I HAVE to get acces to Item2 (the object of my Tuple) The logical thing that came to my mind was to rewrite my function with :

private void plugin_Selected(object sender, RoutedPropertyChangedEventArgs<Tuple<string, object>> e)

but I got the following error :

No overload for 'plugin_Selected' matches delegate 'System.Windows.RoutedPropertyChangedEventHandler<object>'

So, what can I do to access to Item1 (string) and Item2 (object) values of my Tuple ?

EDIT : I got this test that could be a way to solve the problem

if (e.NewValue.GetType() == typeof(Tuple<string, object>))

but I don't know what to do next cause something like :

object MyObject =  = e.NewValue.Item2;

doesn't compile... :(


Solution

  • Why not cast the e.NewValue to your Tuple?

    private void plugin_Selected(object sender, RoutedPropertyChangedEventArgs<object> e)
    {
        Tuple<string, object> tuple = e.NewValue as Tuple<string, object>;
    }
    

    Using the as operator makes sure that if the cast fails your tuple will be null!