0

我要做的是,获取列表框中所选项目的属性值。

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 代码-

<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>

现在,我想要得到的是选定列表框项的 C_ID(value)。有什么建议么?

4

2 回答 2

2

它会是这样的:

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;
    }
}

Page_Ctor --> listBox1.SelectionChanged += listBox1_SelectionChanged;

干杯,

于 2012-07-03T11:44:38.493 回答
0

我在哪里放置这个“Page_Ctor --> listBox1.SelectionChanged += listBox1_SelectionChanged;”

这里 :

<ListBox .... SelectionChanged="listBox1_SelectionChanged">
于 2012-07-03T12:36:45.007 回答