wpf ListBox绑定数据后如何获得ListBoxItem

xeonfeng 2013-03-27 01:51:11
绑定数据的Listbox如何获取到当前选中的ListBoxItem,如下代码获取到的是VedioScreen的实体。
请教如何获取当前选中的listboxItem项?

XAML:
<ListBox x:Name="PlayListBox" ItemsSource="{Binding VedioScreenList,Mode=TwoWay}" 
SelectedItem="{Binding VedioScreenItem}" SelectionMode="Single"
ItemContainerStyle="{StaticResource ListBoxItemStyle}"
SelectionChanged="PlayListBox_SelectionChanged" />


C#:
 void PlayListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
VedioScreen vs = PlayWndListBox.SelectedItem as VedioScreen;
var lstitem = (sender as ListBox).SelectedItem as ListBoxItem; //这里lstitem是null
}
...全文
630 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
xeonfeng 2013-03-28
  • 打赏
  • 举报
回复
引用 4 楼 ariesget 的回复:
你绑定的又不是ListBoxItem类型的自然获得不到ListBoxItem类型的。 绑定的是什么类型你的SelectedItem就是什么类型啊。 VedioScreen lstitem = (sender as ListBox).SelectedItem as VedioScreen; 你是指要获得UI上包装你这个SelectedItem的ListBoxItem控件?
是的,需要获取ListBoxItem控件
ariesget 2013-03-28
  • 打赏
  • 举报
回复
你绑定的又不是ListBoxItem类型的自然获得不到ListBoxItem类型的。 绑定的是什么类型你的SelectedItem就是什么类型啊。 VedioScreen lstitem = (sender as ListBox).SelectedItem as VedioScreen; 你是指要获得UI上包装你这个SelectedItem的ListBoxItem控件?
ariesget 2013-03-28
  • 打赏
  • 举报
回复
6楼给出正解了。 ListBox ls = sender as ListBox; ListBoxItem lstitem = ls.ItemContainerGenerator.ContainerFromItem(ls.SelectedItem) as ListBoxItem;
ktei2008 2013-03-28
  • 打赏
  • 举报
回复
引用 5 楼 xeonfeng 的回复:
[quote=引用 4 楼 ariesget 的回复:] 你绑定的又不是ListBoxItem类型的自然获得不到ListBoxItem类型的。 绑定的是什么类型你的SelectedItem就是什么类型啊。 VedioScreen lstitem = (sender as ListBox).SelectedItem as VedioScreen; 你是指要获得UI上包装你这个SelectedItem的ListBoxItem控件?
是的,需要获取ListBoxItem控件[/quote] 不知道你的具体需求是什么,但是一般来讲,你并不需要获取具体的ListBoxItem,能绑定就绑定。但是既然你问到了,你可以这样做: listBox.ItemContainerGenerator.ContainerFromItem或listBox.ItemContainerGenerator.ContainerFromIndex
xeonfeng 2013-03-27
  • 打赏
  • 举报
回复
引用 1 楼 DENQH 的回复:
DataRowView lstitem = (sender as ListBox).SelectedItem as DataRowView; string str=lstitem["绑定字段名"].ToString();
lstitem 返回为Null。。。 需要获取的是 被选中的ListBoxItem 控件项
DENQH 2013-03-27
  • 打赏
  • 举报
回复
DataRowView lstitem = (sender as ListBox).SelectedItem as DataRowView; string str=lstitem["绑定字段名"].ToString();

110,533

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧