C# 如何获取所选列表框项的值
我正在将xml文件中的数据加载到列表框中。这是我的xamlC# 如何获取所选列表框项的值,c#,windows-phone-8,C#,Windows Phone 8,我正在将xml文件中的数据加载到列表框中。这是我的xaml <ListBox x:Name="lstSearchCategory" FontFamily="Arial Black" VerticalAlignment="Center" Margin="25,69,19,10" Height="264"> <ListBox.ItemTemplate> <DataTemplate> <Sta
<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>
这很好用。现在我想知道,当我选择任何列表框项目时,我会得到它各自的值,即图像、价格、类别等。我该怎么做?帮助如果通过绑定填充
列表框
,则视图模型中应该有一些属性lileSelectedItem
。因此,当前选定的项目应始终存储在viewmodel中,以便于访问。只需向viewmodel中的SelectedItem添加一个绑定,一切都应该正常工作。您需要在ListBox事件中获取所选项目,并从ListBox获取数据模板(如上所示):
private void lstEvents\u SelectionChanged(对象发送者,SelectionChangedEventArgs e)
{
ListBoxItem lbi=(lstEvents.ItemContainerGenerator.ContainerFromIndex(lstEvents.SelectedIndex))作为ListBoxItem;
ContentPresenter cp=GetFrameworkElementByName(lbi);
DataTemplate dt=lstEvents.ItemTemplate;
标签l=(dt.FindName(“lbleventi”,cp))作为标签;
Show(l.Content.ToString());
}
您需要在XAML文件中生成Tap=“lstSearchCategory\u 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">
这里class name是绑定name、price等值的类的名称它在GetFrameworkElementByName和FindName处的给定错误您可以看看下面的示例。你能告诉我密码吗?我不知道如何获得选定的类别等
<ListBox Tap="lstSearchCategory_Tap" x:Name="lstSearchCategory">
var selected = (classname)lstSearchCategory.SelectedValue;
MessegeBox.Show(selected.Name + selected.Price);