【问题标题】:Find Index of Item in ItemsControl nested inside a LixtBox.Item在嵌套在 LixtBox.Item 内的 ItemsControl 中查找项目索引
【发布时间】:2014-02-21 19:22:54
【问题描述】:

我有一个 ItemsControl 嵌套在 ListBox.ItemTemplate 中。顶部的ListBox 数据绑定到ObservableCollection。该集合本质上是一个购买,其中包含公式,而公式又包含单个产品。

现在,如果单击公式中的单个产品,我希望将其从公式中删除。因此,在事件处理程序中,我应该能够使用以下方法确定产品的位置:

var index = [theItemsControl].ItemContainerGenerator.IndexFromContainer((sender as Button).TemplatedParent);

但是,在我的事件处理程序中,我不知道如何找到包含的ItemsControl。我不能给它一个固定的名字,因为它本身就是ListBox.ItemTemplate 的一部分,这意味着会有多个实例。

这是我的 XAML,去掉了任何与样式相关的东西:

<ListBox x:Name="lbBasketFormulae" ItemsSource="{Binding Path=Purchase.Formulae}">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <StackPanel Orientation="Vertical">

        <!-- Formula Title -->
        <StackPanel Orientation="Horizontal">
          <Label Width="30" Content="{Binding Path=Quantity}"></Label>
          <Label Content="{Binding Path=FormulaType, Converter={StaticResource formulaTypeToNameConverter}}"></Label>
        </StackPanel>

        <!-- Formula Products -->
        <ItemsControl ItemsSource="{Binding Path=Products}">
          <ItemsControl.ItemTemplate>
            <DataTemplate>
              <Button x:Name="bnBasketFormulaProduct" HorizontalContentAlignment="Left" Content="{Binding Path=Name}" Click="bnBasketFormulaProduct_Click">
                <Button.Template>
                  <ControlTemplate TargetType="Button">
                    <TextBlock Text="{TemplateBinding Content}" />
                  </ControlTemplate>
                </Button.Template>
              </Button>
            </DataTemplate>
          </ItemsControl.ItemTemplate>
        </ItemsControl>

      </StackPanel>
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

所以,我的问题是:如何找到我的产品在我的公式中的位置以及该公式在购买中的位置,以便我可以从ObservableCollection 中删除它? (更改集合应该会自动反映到 UI,因为它是数据绑定的。)

非常感谢您提供任何建议或提示!

问候,

克里斯

【问题讨论】:

    标签: c# wpf xaml itemscontrol


    【解决方案1】:

    确实,您应该能够通过视图模型来做到这一点。但如果你愿意,你可以使用:

    VisualTreeHelper.GetParent(myUserControl);
    

    【讨论】:

    • 谢谢。使用这种方法,我能够访问父级的数据上下文,这最终比我最初想要的索引更加有用和可靠。
    【解决方案2】:

    答案是使用 ItemContainerGenerator.IndexFromContainer 找不到任何位置。您的问题显然发生在 ViewModel 内部,因此您应该在 ViewModel 中寻找选定的项目或任何内容,而不是在 ListBox 或 Window 后面的代码中。

    因此,我建议您使用适当的 Bindings 创建适当的 ViewModel。

    【讨论】:

    • 谢谢,但我目前没有实现 MVVM 模式。我是 WPF/XAML 的新手,这已经够难了。
    • 我能理解你想让事情变得简单。我有时想揍那个说服我们迁移到 WPF 的人,因为简单的事情可能需要更长的时间。但是请注意,您的逻辑不会与您的控件绑定,因为这会导致更多的工作。 WPF 错误发现并不好。请参阅此线程以获取一些真正帮助我的优秀技巧:stackoverflow.com/questions/8863840/…
    猜你喜欢
    • 2014-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-17
    • 1970-01-01
    • 2023-04-10
    • 2016-01-25
    相关资源
    最近更新 更多