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

本文关键字:列表 项目 何获取 获取 | 更新日期: 2023-09-27 18:22:03

我正在将数据从xml文件加载到列表框中。这是我的xaml

<ListBox x:Name="lstSearchCategory" FontFamily="Arial Black" 
         VerticalAlignment="Center" Margin="25,69,19,10" Height="264">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel >
                <Image Source="{Binding Image}" Height="100" Width="100" 
                       HorizontalAlignment="Left"></Image>
                <TextBlock HorizontalAlignment="Right" Text="{Binding Name}" 
                           FontSize="30" Foreground="Black" Margin="140,-100,0,0"/>
                <TextBlock Text="{Binding Category}" FontSize="24" 
                           Foreground="Black" Margin="10,-10,0,0"/>
                <TextBlock Text="{Binding Price}" HorizontalAlignment="Right" 
                           Foreground="Red" Margin="300,-25,0,16"/>
                <Rectangle Width="500"  Fill="Black" Height="0.5"/>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

这很好用。现在我想,当我选择任何列表框项目时,我都会得到它各自的值,即图像、价格、类别等。我该怎么做?帮助

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

您需要在ListBox事件中获取所选项目,并从ListBox中获取DataTemplate(如MSDN上所示):

private void lstEvents_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ListBoxItem lbi = (lstEvents.ItemContainerGenerator.ContainerFromIndex(lstEvents.SelectedIndex)) as ListBoxItem;
            ContentPresenter cp = GetFrameworkElementByName<ContentPresenter>(lbi);
            DataTemplate dt = lstEvents.ItemTemplate;
            Label l = (dt.FindName("lblEventId", cp)) as Label;
            MessageBox.Show(l.Content.ToString());   
        }

您需要在XAML文件中生成Tap = "lstSearchCategory_Tap",并在.cs文件中生成以下代码

private void lstSearchCategory_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
    try
    {
        ListBox ListBoxSelecteditem = (ListBox)sender;
        YourModel model = (YourModel)ListBoxSelecteditem.SelectedItem;            
        string name = model.Name;
        string cat = model.Category;
        .......
        string ControlName = ((System.Windows.FrameworkElement)
                             (((System.Windows.RoutedEventArgs)(e)).OriginalSource)).Name;
        if (ControlName.ToLower() != "name".ToLower())
        {
        }
    }
    catch (Exception ex)
    { }
}   

尝试这个

<ListBox Tap="lstSearchCategory_Tap" x:Name="lstSearchCategory">

然后添加这个

    var selected = (classname)lstSearchCategory.SelectedValue;
   MessegeBox.Show(selected.Name + selected.Price);

这里的类名是绑定名称、价格等值的类名

如果通过绑定填充ListBox,则视图模型中应该有一些属性lile SelectedItem。因此,当前选择的项目应始终存储在视图模型中,以便于访问。只要在视图模型中为SelectedItem添加一个绑定,一切都会正常工作。