Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Silverlight ItemsControl behavior: how do i get an item i click on?

I'm creating a behavior for an ItemsControl with the purpose of selecting the item i click on (and adding it to a list of selected items).

So it's easy to get all the items:

hours = AssociatedObject.ItemsSource as List<Hour>;

and of course i could write hours[0].Selected = true;

but then I've got a mouse event, that i tried writing something like this:

void AssociatedObject_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        hour = sender as Hour;
    }

the problem is, it's not working like i expected... the sender is not an Hour, it's an ItemsControl.

and I've got no indication as to which hour was clicked. so what should i do to get the hour?

Edit My code works like this: there's an ItemsControl bound to a list of Days. each day has a list of hours. and to represent that, there is an inner ItemControl bound to (day.)Hours. and to represent each hour, there's a border.

looks like this:

 <ItemsControl x:Name="daysPanel" Grid.Column="1" ItemsSource="{Binding Days}">
       <ItemsControl.ItemTemplate>
            <DataTemplate>
                <ItemsControl x:Name="dayHours" ItemsSource="{Binding Hours}" Grid.Row="1">
                     <ItemsControl.ItemTemplate>
                            <DataTemplate>
                                  <Border Name="dayHourBorder" Tag="{Binding}" Height="30" BorderBrush="#B0B6BE" Width="193" BorderThickness="1,0,1,1" Background="{Binding Path=Selected, Converter={StaticResource boolToColorConverter}}" >
like image 599
Notter Avatar asked Jan 20 '23 11:01

Notter


2 Answers

thanks everyone for trying to help, but i found the right way to do it. i knew there had to be simple way to get the UI element that was clicked on, there just had to be one!

and there was! instead of working with the sender, you just have to do: e.OriginalSource

that got me the border (and the hour that's bounded to it). so it's as "simple" as:

(e.OriginalSource as Border).DataContext as Hour
like image 143
Notter Avatar answered Feb 07 '23 10:02

Notter


VisualTreeHelper may be useful for you. You can use to get all elements at point, where mouse clicked and get your Border. Its tag is binded to Hours, so you can get it.
Get the ItemsControl of a DataTemplate from SO and VisualTreeHelper from http://blogs.msdn.com must help you.

like image 35
Samvel Siradeghyan Avatar answered Feb 07 '23 11:02

Samvel Siradeghyan