简体   繁体   English

如何获取所选列表框项的属性值

[英]How to get property value of selected list box item

What I am trying to do is, get the property value of the selected item in the list box. 我要做的是,获取列表框中所选项的属性值。

private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
    //listBox1.Items.Clear();

    IList<FoodViewModel> food = this.Getfoodlist();    
    List<Foodlist> foodItems = new List<Foodlist>();

    foreach (FoodViewModel foodlist in food)
    {
        int foodID = foodlist.C_ID;
        string foodDetail = foodlist.FoodDetail;
        string foodTime = foodlist.FoodTime;
        string foodDate = foodlist.DateofFood;

        foodItems.Add(new Foodlist() { C_ID = foodID, FoodTime = foodTime, DateofFood = foodDate, FoodDetail = foodDetail}); 
    }

    listBox1.ItemsSource = foodItems;
}

public class Foodlist
{
    public int C_ID { get; set; }
    public string DateofFood{ get; set;}    
    public string FoodTime{ get; set;}    
    public string FoodDetail{ get; set;}
}

XAML CODE- XAML代码 -

<ListBox Height="528" HorizontalAlignment="Left" Margin="1,4,0,0" Name="listBox1" VerticalAlignment="Top" Width="453">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock Name="foodDetail"
                           Text="{Binding FoodDetail}" />
                <TextBlock Name="date"
                           Text="{Binding DateofFood}" />
                <TextBlock Name="time"
                           Text="{Binding FoodTime}" />
                <TextBlock Name="ID"
                           Text="{Binding C_ID}" Visibility="Collapsed" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Now, what I want to get is the C_ID(value) of selected listbox item. 现在,我想要的是所选列表框项的C_ID(值)。 Any suggestions? 有什么建议么?

It would be something like this: 它会是这样的:

private void listBox1_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
    if (e.AddedItems.Count > 0)
    {
        var c_id = (e.AddedItems[0] as Foodlist).C_ID;
    }
}

and

Page_Ctor --> listBox1.SelectionChanged += listBox1_SelectionChanged;

cheers, 干杯,

where do I place this "Page_Ctor --> listBox1.SelectionChanged += listBox1_SelectionChanged;" 我在哪里放置“Page_Ctor - > listBox1.SelectionChanged + = listBox1_SelectionChanged;”

Here : 这里 :

<ListBox .... SelectionChanged="listBox1_SelectionChanged">

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

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