简体   繁体   English

c#WPF从列表框中选择的项目绑定到数据表

[英]c# WPF selected item from listbox bound to datatable

I'm building a wpf application and I made my database using Entity Framework code first. 我正在构建一个wpf应用程序,并且首先使用Entity Framework代码创建了数据库。

I have a list box bound to a table 我有一个绑定到表的列表框

XAML XAML

<ListBox x:Name="lstDishes" Height="415" VerticalAlignment="Bottom" Margin="0,0,1032,42" HorizontalAlignment="Right" Width="281" ItemsSource="{Binding}" Background="#FFDDC9B0" BorderBrush="{x:Null}" FontSize="15" MouseDoubleClick="lstDishes_MouseDoubleClick">

XAML.CS XAML文件

var dish = (from Dish in db.Dishes
            select Dish).ToList();
lstDishes.ItemsSource = dish;
lstDishes.DisplayMemberPath = "Description";

On item double click, I would like to show selected item in another listbox. 在项目双击上,我想在另一个列表框中显示选定的项目。

I was trying to manage it, but before I was doing some kind of trial for the selected item, showing a message box on double click 我试图进行管理,但是在对所选项目进行某种试验之前,双击显示一个消息框

private void lstDishes_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
   MessageBox.Show("You selected: " + lstDishes.SelectedItem.ToString());
}

But the result of my messagebox is this: 但是我的消息框的结果是这样的:

在此处输入图片说明

Of course it's not readable. 当然是不可读的。

  • How can I get the selected item as it's shown in listbox? 如何获得列表框中显示的所选项目?

  • Do you have any suggestion for the next step where I'm going to binde the selected item to another listbox? 您对下一步将所选项目绑定到另一个列表框有什么建议吗?

Edit 编辑

Since my listbox is bound to a table in database, I had to cast the selected item as my type of entity. 由于我的列表框绑定到数据库中的表,因此我不得不将所选项目强制转换为我的实体类型。

You need to get the type of the selected item and 您需要获取所选项目的类型,然后

private void lstDishes_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
   var Selected =  lstDishes.SelectedItem as Dish;
   MessageBox.Show("You selected: " + Selected.Description));   
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM