C# 处理列表项中的选定项
在WPF中,列表项包含一些项,当选择C# 处理列表项中的选定项,c#,wpf,C#,Wpf,在WPF中,列表项包含一些项,当选择列表项中的某个项时,我需要处理所选项上的一些事件 private void Button_Click_1(object sender, RoutedEventArgs e) { string y = this.LBOX.SelectedItem.ToString(); MessageBox.Show(y); } 创建获取选定项的方法后 private void Button_Click_1(object s
列表项中的某个项时,我需要处理所选项上的一些事件
private void Button_Click_1(object sender, RoutedEventArgs e)
{
string y = this.LBOX.SelectedItem.ToString();
MessageBox.Show(y);
}
创建获取选定项的方法后
private void Button_Click_1(object sender, RoutedEventArgs e)
{
string y = this.LBOX.SelectedItem.ToString();
MessageBox.Show(y);
}
此方法显示:System.Windows.Control.ListBoxItem.List1
您需要强制转换SelectedItem
假设你有以下几点
class Items
{
string Name {get; set; }
string Address { get; set; }
}
您已将其分配给您的控件。
要访问这些值,您需要执行以下操作
//check that we have an item selected
//then check if item is of type Items, if not the cast below will error
if (LBOX.SelectedItem != null && LBOX.SelectedItem is Items)
{
Items selectedItem = LBOX.SelectedItem as Items;
}
看起来您正在将字符串存储在ListBoxItems
中,SelectedItem
属性实际上返回了一个对象,您需要将该对象强制转换为ListBoxItem
,以便访问Content
属性,然后对其使用ToString
方法。像这样的东西应该适合你
string y = ((ListBoxItem)LBOX.SelectedItem).Content.ToString();