问题
鉴于这段代码,我想在按下它时访问ListBoxItem
包含 a的属性(更具体地说,它的索引)。Button
我认为我需要获取Button
' 的父级(它是一个StackPanel
),然后是它的父级TemplatedParent
,然后沿着 Visual Tree 向上走,但我不知道两件非常重要的事情:如何有效地解决我的问题,这是否真的解决了我的问题。
XAML
<ListBox x:Name="myListBox" Foreground="Black" HorizontalAlignment="Left" Height="101" Margin="237,312,0,0" VerticalAlignment="Top" Width="420">
<ListBox.ItemTemplate>
<!--src is the alias I gave to the xmlns that gives me access to the assembly on which I'm working-->
<DataTemplate DataType="{x:Type src:Items}">
<DataTemplate.Resources>
<Style TargetType="Label">
<Setter Property="Foreground" Value="Black"/>
<Setter Property="FontFamily" Value="Tahoma"/>
</Style>
</DataTemplate.Resources>
<StackPanel Orientation="Horizontal">
<!--Property1 to Property3 are defined in the Items type-->
<Label Content="{Binding Path=Property1}" Width="30" MaxWidth="30"/>
<Label Content="{Binding Path=Property2}" Width="100" MaxWidth="100"/>
<Label Content="{Binding Path=Property3}" Width="250" MaxWidth="250"/>
<Button Content="X" Width="30" MaxWidth="30" Click="RemoveItemFromList"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
C夏普
我的一段代码可以正常工作
//Somewhere in my code
ObservableCollection<Items> myStuff = createListOfItems();
myListBox.DataContext = myStuff;
myListBox.setBinding(ItemsControl.ItemsSourceProperty, new Binding());
我认为可能是答案(不工作)
private void RemoveItemFromList(object sender, RoutedEventArgs e)
{
int index = (((sender as Button).Parent as StackPanel).TemplatedParent as ListBoxItem).IsSelected = true;
myStuff.RemoveAt(myListBox.SelectedIndex);
}