Reputation: 1996
I have a listbox with a custom stackpanel (just a class extended a stackpanel now but i am hoping to do some animation here) as its itemspanel. Now when the selection changes I thought of doing some nice animation between the last selected item and the current selected item.
Now my problem is how do I get hold of the selected item in the itemspanel?
This is how I am defining my itemspanel
<ItemsPanelTemplate>
<l:CustomStackPanel SelectedItem="{Binding SelectedItem,ElementName=listbox}" IsItemsHost="True" Orientation="Vertical"/>
</ItemsPanelTemplate>
I created a dependencyproperty in my custom stackpanel called SelectedItem
public UIElement SelectedItem
{
get { return (UIElement)GetValue(SelectedItemProperty); }
set { SetValue(SelectedItemProperty, value); }
}
// Using a DependencyProperty as the backing store for SelectedItem. This enables animation, styling, binding, etc...
public static readonly DependencyProperty SelectedItemProperty =
DependencyProperty.Register("SelectedItem", typeof(UIElement), typeof(CustomStackPanel), new PropertyMetadata(null,selectionChanged));
And I thought I could simply bind the selectedItem in my listbox to the selecteditem in the stackpanel. But this approach is simply not working.
Another thought was to override previewmousedown on the stackpanel and find the corresponding item from the Children of the stackpanel. But again I am not sure how to find the item.
Upvotes: 2
Views: 305
Reputation: 18580
Use RelativeSource in your binding
<ItemsPanelTemplate>
<l:CustomStackPanel SelectedItem="{Binding SelectedItem,RelativeSource={RelativeSource FindAncestor, AncestorType=x:Type ListBox}}" IsItemsHost="True" Orientation="Vertical"/>
</ItemsPanelTemplate>
Upvotes: 1