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

526 Views Asked by At

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... :(

2

There are 2 best solutions below

0
On BEST ANSWER

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!

0
On

Just cast e.NewValue to the correct type:

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

Of course this will produce an exception of the cast is used incorrectly, but that's another issue entirely. You can either use it as is because it will work in this particular scenario, or abstract it if you intend to use this handler for other item types as well.