获取可绑定集合中物品的索引
问题描述:
在此列表框中,我显示联系人姓名。获取可绑定集合中物品的索引
<ListBox x:Name="Items" Margin="36,38,78,131">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock x:Name="lol" Text="{Binding Path=ContactName}" Style="{StaticResource PhoneTextSmallStyle}"
Width="Auto" TextAlignment="Center" FontWeight="Bold" Foreground="White" VerticalAlignment="Bottom" TextWrapping="Wrap"/>
<Button x:Name="ShowName">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<cal:ActionMessage MethodName="delete" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
我得到的接触从本地数据库
public List<FBContacts> listContactDatas { get; set; }
Items = new BindableCollection<FBContacts>();= new BindableCollection<FBContacts>();
public void GetContacts()
{
using(MyDataContext mydb = new MyDataContext(DBConnectionstring))
{
var items = from ContactsList Name in mydb._contacts select Name;
foreach (var toDoItem in items)
{
Items.Add(new FBContacts()
{
ContactName = toDoItem.Name
});
}
}
}
用户可以删除任何接触,如果他按下按钮。
public void delete()
{
Items.RemoveAt(/* index*/);
}
所以如何我可以得到选择联系索引?
答
如果您通过单击的FBContacts
到delete
方法更容易通过FBContacts
对象而不是索引:
public void delete(FBContacts item)
{
Items.Remove(item);
}
答
绑定当前选择的项目的索引到一个单独的属性:
<ListBox x:Name="Items" SelectedIndex="{Binding SelectedListIndex}" Margin="36,38,78,131">
当然,SelectedListIndex
必须定义为int
类型,在视图模型激发PropertyChanged
的属性。
然后,您可以轻松地随时随地访问视图模型中所选项目的索引:
<Button x:Name="ShowName">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<cal:ActionMessage MethodName="delete">
<cal:Parameter Value="{Binding}" />
</cal:ActionMessage>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
然后你就可以删除:
public void delete()
{
Items.RemoveAt(SelectedListIndex);
}
更改选择时,SelectedListIndex属性是否更新(例如,Setter上的断点)?也许你需要添加'SelectedIndex =“{Binding SelectedListIndex,Mode = TwoWay}”'强制更新属性 – andreask 2014-09-03 07:59:54
我得到这个错误 System.Reflection.TargetInvocationException“in System.Windows.ni.dll – 2014-09-03 08:07:29
也许列表的选择是在创建SelectedListIndex之前就已经改变了。你如何填充列表?是否通过数据绑定来设置列表项? – andreask 2014-09-03 08:30:50