2

我有一个带有自定义堆栈面板的列表框(现在只是一个扩展堆栈面板的类,但我希望在这里做一些动画)作为它的项目面板。Now when the selection changes I thought of doing some nice animation between the last selected item and the current selected item.

现在我的问题是如何在项目面板中获取所选项目?

这就是我定义我的项目面板的方式

<ItemsPanelTemplate>
                    <l:CustomStackPanel SelectedItem="{Binding SelectedItem,ElementName=listbox}"  IsItemsHost="True" Orientation="Vertical"/>
                </ItemsPanelTemplate>

我在我的自定义堆栈面板中创建了一个名为 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));

而且我认为我可以简单地将列表框中的 selectedItem 绑定到堆栈面板中的 selecteditem。但这种方法根本行不通。

另一个想法是覆盖 stackpanel 上的 previewmousedown 并从 stackpanel 的Children中找到相应的项目。但我又不知道如何找到该项目。

4

1 回答 1

1

在绑定中使用 RelativeSource

<ItemsPanelTemplate>
     <l:CustomStackPanel SelectedItem="{Binding SelectedItem,RelativeSource={RelativeSource FindAncestor, AncestorType=x:Type ListBox}}"  IsItemsHost="True" Orientation="Vertical"/>
 </ItemsPanelTemplate>
于 2014-06-26T09:35:44.430 回答