I have a ListBox
that its ItemsSource
is given from a class based on the data binded items template. I want to find ListBox.SelectedItem
position relative to the ListBox
. Since I've used a class to feed ItemsSource
, I'm not be able to cast ListBox.SelectedItem
(which has a type of object
) to the ListBoxItem
. (Instead I should cast it to the source class type.)
What's the way? -Thanks
Details: (Arbitrary)
There is a ListBox
which implements a Style
like so:
<Style x开发者_运维技巧:Key="MyListBoxStyle" TargetType="{x:Type ListBox}">
<Setter Property="ItemTemplate">
<Setter.Value>
<DataTemplate>
<Border ...>
<StackPanel ...>
<Image Source="{Binding Path=ItemImageSource}" .../>
<TextBlock Text="{Binding Path=ItemTitle}" .../>
</StackPanel>
</Border>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
The ListBox
has been used as follows:
<ListBox x:Name="MyListBox"
ItemsSource="{Binding}"
Style="{StaticResource ResourceKey=MyListBoxStyle}"/>
Also there is a class that supports MyListBox
data-binding info:
internal class MyListBoxItemBinding
{
public string ItemTitle { get; set; }
public ImageSource ItemImageSource { get; set; }
}
And to feed the MyListBox
:
MyListBox.ItemsSource = new List<MyListBoxItemBinding> { /* some items */ };
Now, how can I find MyListBox.SelectedItem
location relative to the MyListBox
?
Use ItemsControl.ItemContainerGenerator
to get a reference to the item container generator for your ListBox
(this is the object that creates wrappers for all your databound objects).
Then, use the ItemContainerGenerator.ContainerFromItem
method to get a reference to the UIElement
that represents the selected ListBoxItem
.
Finally, see the answer to this question to for a way of getting the coordinates of the selected item relative to the ListBox
.
精彩评论