[英]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,每個都包含一個ListBoxItem
。 SelectedItem
包含的內容生成的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.