【发布时间】: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