WPF-如何从数据绑定ListBox中获取Listbox项和selectedvalue [英] WPF- How to get Listbox item and selectedvalue from a data bound ListBox

查看:980
本文介绍了WPF-如何从数据绑定ListBox中获取Listbox项和selectedvalue的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨朋友,



任何人请告诉我如何从数据绑定列表框中获取所选值和项目



请帮帮我,提前致谢。



XAML代码



Hi Friends,

Anyone please let me know how to get the selected value and item from a data bound ListBox

Please help me, Thanks in advance.

XAML code

<ListBox x:Name="listbox1" Width="150" ItemsSource="{Binding Things}" DisplayMemberPath="department_name" SelectedValuePath="department_id" Margin="12,35,326,12"  />





C#

数据绑定与数据集





C#
Data binding with Dataset

listbox1.DisplayMemberPath = "department_name";
listbox1.SelectedValuePath = "department_id";
listbox1.ItemsSource = ds.Tables[0].DefaultView;







输出






Output

MessageBox.Show(listbox1.Items.CurrentItem.ToString());//Output -System.Data.DataRowView
MessageBox.Show(listbox1.SelectedItem.ToString());////Output -System.Data.DataRowView
MessageBox.Show(listbox1.SelectedValue.ToString());//Object reference not set to an instance of an object.

推荐答案

您好kznaneswar,您的ListBox中是否有任何选定的项目?

Hi kznaneswar, Have you got any selected item in your ListBox?
MessageBox.Show(listbox1.SelectedValue != null ? listbox1.SelectedValue.ToString() : "I have 0 selected item!"); // If the selected value is null print a custom message.



编辑(根据您的评论) .-

在您的Selection_Changed事件中写下:


Edit(based on your comment).-
Inside your Selection_Changed event write this:

if (listbox1.SelectedItem!=null)
{
    MessageBox.Show(listbox1.Items.CurrentItem.ToString());//Output -System.Data.DataRowView
    MessageBox.Show(listbox1.SelectedItem.ToString());////Output -System.Data.DataRowView
    MessageBox.Show(listbox1.SelectedValue != null ? listbox1.SelectedValue.ToString() : "I have 0 selected item!");
}



另一种方法。这将起作用!


Another approach. This going to work!

if (listbox1.SelectedItem!=null)
{
    DataRowView d1=listbox1.SelectedItem as DataRowView;
    MessageBox.Show(d1["department_id"].tostring());
}





希望有所帮助。



Hope it helps.


这篇关于WPF-如何从数据绑定ListBox中获取Listbox项和selectedvalue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆