繁体   English   中英

单击按钮获取所选ListBoxItem的名称

[英]Get Name of Selected ListBoxItem on Button Click

我是WPF / C#的新手,我正在尝试创建一个简单的sql查询应用程序以适应它。 我的XAML中有一个列表框和一个对应的按钮:

<ListBox Name="dbTables" Grid.Column="1" Grid.Row="2">
        <ListBoxItem>Log</ListBoxItem>
        <ListBoxItem>DownloadRequest</ListBoxItem>
        <ListBoxItem>EmailRequest</ListBoxItem>
    </ListBox>

    <!-- View report button -->
    <Button x:Name="myButton" Grid.Column="1" Grid.Row="3" Margin="0,10,0,0" Width="125" Height="25" HorizontalAlignment="Right" Click="Button_Click">View</Button>

和相应的C#函数:

 private void Button_Click(object sender, RoutedEventArgs e)
    {
        String curItem = dbTables.SelectedValue.ToString();

        Console.WriteLine("CurItem = " + curItem);
        Results resultsPage = new Results(curItem);
        this.NavigationService.Navigate(resultsPage);

    }

但是,当输出CurItem时,它具有以下值:

CurItem = System.Windows.Controls.ListBoxItem: Log

当我尝试运行SQL查询时,它将引发异常。 我试图让它只是CurItem = Log

我尝试了几种不同的方法,但似乎没有附加对象定义就无法仅获得所选值的名称。

SelectedItem返回列表框中当前选择的项目。 由于您要使用ListBoxItem填充列表框,因此它将返回结果。 (请注意,顺便说一下,你的列表框中会自动生成ListBoxItem容器的项目-如果你在视觉树看,你会发现,这个ListBox包含ListBoxItem S,每个都包含一个ListBoxItemSelectedItem包含的内容生成的ListBoxItem ,也就是说您正在标记中创建的ListBoxItem 。)

SelectedValue返回ListBox.SelectedValuePath指定的SelectedItem属性的值。 如果未提供SelectedValuePath ,则它返回SelectedItem ,因此,如果您不了解SelectedValuePath ,似乎两者是同一回事。 但是,如果用例如Person对象填充列表,并将SelectedValuePath设置为"Name" ,则SelectedValue将包含所选人员的姓名,而不是对Person对象的引用。

因此,在您的示例中,您可以通过将SelectedValuePath设置为"Content"来使SelectedValue返回字符串,该属性是包含正在使用的字符串的ListBoxItem的属性。

您可以通过不显式创建ListBoxItem而仅使用字符串填充ListBox另一种方式。 您必须声明一个引用mscorlib的名称空间才能执行此操作,以便可以在XAML中表示字符串对象,但是一旦执行,结果就很简单:

<Page
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:sys="clr-namespace:System;assembly=mscorlib">
  <DockPanel>  
    <ListBox DockPanel.Dock="Top" Margin="10" x:Name="test" SelectedValuePath="Length">
      <sys:String>Log</sys:String>
      <sys:String>DownloadRequest</sys:String>
      <sys:String>EmailRequest</sys:String>
    </ListBox>
    <TextBlock DockPanel.Dock="Top" Margin="10" Text="{Binding ElementName=test, Path=SelectedItem}"/>    
    <TextBlock DockPanel.Dock="Top" Margin="10" Text="{Binding ElementName=test, Path=SelectedValue}"/>    
  </DockPanel>
</Page>

Selected Value是一个ListBoxItem,因此您可以将该值转换为ListBoxItem,然后使用Content属性:

ListBoxItem selItem = (ListBoxItem)dbTables.SelectedValue;

        Console.WriteLine(selItem.Content);
String curItem = (dbTables.SelectedValue as ListBoxItem).Content.ToString();

暂无
暂无

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

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