silverlight/windows phone 7选择列表框内按钮存在索引问题
我有一个列表框,里面有一个简单的项目列表。在我的xaml页面上,我有以下内容silverlight/windows phone 7选择列表框内按钮存在索引问题,silverlight,listbox,windows-phone-7,Silverlight,Listbox,Windows Phone 7,我有一个列表框,里面有一个简单的项目列表。在我的xaml页面上,我有以下内容 <ListBox Name="listBox1"> <ListBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding firstName}"/
<ListBox Name="listBox1">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding firstName}"/>
<TextBlock Text="{Binding lastName}"/>
<Button BorderThickness="0" Click="buttonPerson_Click">
<Image Source="delete-icon.png"/>
</Button>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
但是,无论我在哪一行单击“删除”按钮,selectedIndex始终为-1
我错过了什么
提前谢谢 该按钮正在捕获触摸(单击)事件,因此该项目永远不会被选中
您不应该使用SelectedIndex,而应该根据单击的按钮确定要删除的项目。(通过查看传递给事件处理程序的
发送方执行此操作。)发送方将是您单击的按钮,其数据上下文将是您要删除的项目,典型的列表
实现将有一个删除
方法。因此,在一般情况下,类似这样的方法是可行的:-
((IList)myPersonList).Remove(((Button)sender).DataContext);
通过将按钮的Tag属性设置为对象,可以执行以下操作:
<Button BorderThickness="0" Click="buttonPerson_Click" Tag="{Binding BindsDirectlyToSource=True}">
<Image Source="delete-icon.png"/>
</Button>
不确定Person对象的名称,因此我没有对其进行标记,但您可能必须这样做,但看起来您对此很满意
XAML中是否缺少StackPanel开始元素?这可能只是一个疏忽,但如果这是您的实际代码,可能会给您带来一些问题。我知道您有答案,但这是另一种解决问题的方法。
您还可以使用selecteditem属性
private void buttonPerson_Click(object sender, RoutedEventArgs e)
{
// Select the item in the listbox that was clicked
listBox1.SelectedItem = ((Button)sender).DataContext;
// If selected index is -1 (no selection) do nothing
if (listBox1.SelectedItem == null)
return;
// Cast you bound list datatype.
myPersonList.remove(([myPersonList Type])listBox1.SelectedValue);
}
这个答案非常有用。如果我不想将整个对象附加到标记,该怎么办?如果我只想附加一个数字..比如..selectedIndex呢?我会避免使用索引(这两种情况都是因为这样做比较困难,而且随着代码的更改,灵活性也会降低)。您可以向自定义对象添加一个ID属性(一些独特的东西),并将标记绑定到此属性。然后,您可以在列表中循环并基于此ID删除,或者使用键设置为该ID的字典。
private void buttonPerson_Click(object sender, RoutedEventArgs e)
{
myPersonList.remove((sender as Button).Tag);
}
private void buttonPerson_Click(object sender, RoutedEventArgs e)
{
// Select the item in the listbox that was clicked
listBox1.SelectedItem = ((Button)sender).DataContext;
// If selected index is -1 (no selection) do nothing
if (listBox1.SelectedItem == null)
return;
// Cast you bound list datatype.
myPersonList.remove(([myPersonList Type])listBox1.SelectedValue);
}