在按钮上获取所选ListBoxItem的名称

时间:2011-02-04 18:30:04

标签: c# wpf

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

我尝试了几种不同的方法,但似乎只是在没有附加对象定义的情况下获取所选值的名称。

3 个答案:

答案 0 :(得分:3)

SelectedItem返回列表框中当前选定的项目。由于您使用ListBoxItem填充了列表框,因此它将返回。 (顺便说一下,您的列表框会自动为其项目生成ListBoxItem个容器 - 如果您查看可视树,则会发现此ListBox包含ListBoxItem个,其中每个都包含ListBoxItemSelectedItem包含生成的ListBoxItem的内容,也就是说您在标记中创建的ListBoxItem。)

SelectedValue返回由SelectedItem指定的ListBox.SelectedValuePath属性的值。如果没有给出SelectedValuePath,则返回SelectedItem,所以如果您不了解SelectedValuePath,那么两者似乎是相同的。但是,如果您使用Person个对象填充列表,并将SelectedValuePath设置为"Name",则SelectedValue将包含所选人员的姓名,而不是Person的引用{1}}对象。

因此,在您的示例中,您可以通过将SelectedValue设置为SelectedValuePath来使"Content"返回字符串,这是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>

答案 1 :(得分:2)

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

ListBoxItem selItem = (ListBoxItem)dbTables.SelectedValue;

        Console.WriteLine(selItem.Content);

答案 2 :(得分:0)

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