【问题标题】:Listbox Get SelectedItem in the ItemsPanelListbox在ItemsPanel中获取SelectedItem
【发布时间】: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


【解决方案1】:

在绑定中使用 RelativeSource

<ItemsPanelTemplate>
     <l:CustomStackPanel SelectedItem="{Binding SelectedItem,RelativeSource={RelativeSource FindAncestor, AncestorType=x:Type ListBox}}"  IsItemsHost="True" Orientation="Vertical"/>
 </ItemsPanelTemplate>

【讨论】:

  • Edit - 实际上,只要我将类型从 UIElement 更改为我的实际类型(即 ItemViewModel),它就可以工作。但我需要它作为堆栈面板的 Children 集合中的 UIElement,以便我可以做一些动画。 :(
  • 你不能使用绑定获得 UIelement.. 正如@dkozl 所建议的那样,一旦你按照我的建议获得了选定的项目,你就必须使用 ItemContainerGenerator
猜你喜欢
  • 2013-04-25
  • 2011-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多