C# 在嵌套在LixtBox.Item中的ItemsControl中查找项的索引
我在C# 在嵌套在LixtBox.Item中的ItemsControl中查找项的索引,c#,wpf,xaml,itemscontrol,C#,Wpf,Xaml,Itemscontrol,我在列表框中嵌套了一个ItemsControl。itemstemplate。顶部的列表框是绑定到可观察集合的数据。该系列基本上是一次购买,其中包含配方奶粉,而配方奶粉又包含单个产品 现在,如果单击公式中的单个产品,我希望将其从公式中删除。因此,在事件处理程序中,我应该能够使用以下方法确定产品的位置: var index = [theItemsControl].ItemContainerGenerator.IndexFromContainer((sender as Button).Template
列表框中嵌套了一个ItemsControl
。itemstemplate
。顶部的列表框
是绑定到可观察集合
的数据。该系列基本上是一次购买,其中包含配方奶粉,而配方奶粉又包含单个产品
现在,如果单击公式中的单个产品,我希望将其从公式中删除。因此,在事件处理程序中,我应该能够使用以下方法确定产品的位置:
var index = [theItemsControl].ItemContainerGenerator.IndexFromContainer((sender as Button).TemplatedParent);
但是,在我的事件处理程序中,我不知道如何查找包含的ItemsControl
。我不能给它一个固定的名称,因为它本身是列表框.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>
因此,我的问题是:我如何找到我的产品在我的配方中的位置,以及该配方在购买中的位置,以便我可以将其从可观察集合中删除?(由于集合是数据绑定的,因此更改集合应自动反映到UI。)
非常感谢您的建议和提示
问候,
Chris答案是使用ItemContainerGenerator.IndexFromContainer找不到任何位置。您的问题显然发生在ViewModel中,因此您应该在ViewModel中查找所选项目或任何内容,而不是在窗口的列表框或代码隐藏中
因此,我建议您使用适当的绑定创建一个适当的ViewModel。确实,您应该能够通过ViewModel实现这一点。但如果您愿意,您可以使用:
VisualTreeHelper.GetParent(myUserControl);
谢谢,但是我目前没有实现MVVM模式。我是WPF/XAML的新手,虽然这已经够难了。我能理解你想要保持简单。我有时想揍那个说服我们搬到WPF的家伙,因为简单的事情可能需要更长的时间。但是要小心,不要让你的逻辑与你的控制绑定在一起,因为这会导致更多的工作。WPF bug查找不好。请看这篇文章,了解一些真正帮助我的好建议:谢谢。使用这种方法,我能够访问父级的datacontext,它最终比我最初想要的索引更有用、更可靠。