【发布时间】:2014-08-17 01:53:35
【问题描述】:
我有一个带有自定义堆栈面板的列表框(现在只是一个扩展了堆栈面板的类,但我希望在这里做一些动画)作为它的项目面板。 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。但这种方法根本行不通。
另一个想法是覆盖堆栈面板上的 previewmousedown 并从堆栈面板的 Children 中找到相应的项目。但我又不知道如何找到该项目。
【问题讨论】:
-
如果你使用绑定,那么
SelectedItem将不是UIElement类型,而是绑定列表项类型。Selector.SelectedItem属于Object类型。你想要ListBoxItem吗? -
是的,我想要 ListBoxItem。我的意图是“点亮”当前和先前选定项目之间的项目(就像在选择更改时创建动画路径)。由于 stackpanel 的子项属于 UIElement Collection,我认为所选项目的类型为 UIElement?
-
绑定项目被包裹在
ListBoxItem中用于显示,但SelectedItem(s)保持绑定列表项目类型。您可以使用ItemContainerGenerator.ContainerFromItem(...)从SelectedItem获取ListBoxItem -
谢谢。我认为这为我指明了正确的方向。您认为我可以使用这种方法实现那种动画效果吗?我需要获取最后一个选定项目的索引和当前选定项目的索引。我需要为这两个项目之间的所有项目设置动画。
-
我不认为你可以实现你想要的 - 点亮介于两者之间的项目 - 在纯 XAML 但在代码中是可行的。
标签: wpf listbox stackpanel itemspanel