【问题标题】:Get the ListBoxItem in a ListBox获取 ListBox 中的 ListBoxItem
【发布时间】:2011-04-03 03:31:47
【问题描述】:

当从 ListBox 中选择 ListBoxItem 时,我试图更改它的 Control 模板。为此,我打算从 ListBox 本身中获取选定的 ListBoxItem,并在其上设置控件模板。我该怎么做呢?我已经尝试过 SelectedItem,它返回 ListBoxItem 中的绑定对象。

【问题讨论】:

    标签: c# wpf silverlight silverlight-4.0


    【解决方案1】:

    您可以使用 ItemContainerGenerator 从绑定的项目中检索项目容器:

    object selectedItem = listBox.SelectedItem;
    ListBoxItem selectedListBoxItem = listBox.ItemContainerGenerator.ContainerFromItem(selectedItem) as ListBoxItem;
    

    【讨论】:

    • 这可行,但没有任何效果。 “内容”属性只返回选定的项目对象。我没有得到 ListBox 中的实际单元格。
    【解决方案2】:

    现在你可以这样做了:

    ListBoxItem container = listBox.ContainerFromIndex(listBox.SelectedIndex) as ListBoxItem;
    

    ItemContainerGenerator.ContainerFromItem() 函数现在看起来像 obsolete

    如果您已经为 ListBox 设置了项目模板,那么您可以从

    获取它
    UIElement item= container.ContentTemplateRoot;
    

    【讨论】:

      猜你喜欢
      • 2019-02-09
      • 1970-01-01
      • 2018-07-09
      • 1970-01-01
      • 2012-04-13
      • 1970-01-01
      • 2011-04-10
      • 2012-11-07
      • 1970-01-01
      相关资源
      最近更新 更多