[英]How to get value of selected listbox item
我正在将数据从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文件中以及.cs
文件中的以下代码中生成Tap = "lstSearchCategory_Tap"
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);
这里class-name是要绑定名称,价格等值的类的名称
如果通过绑定填充ListBox
,则视图模型中应具有一些属性lile SelectedItem
。 因此,当前选择的项目应始终存储在视图模型中以便于访问。 只需在您的视图模型中向SelectedItem
添加一个绑定,一切都会正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.