[英]WPF Combobox get selected item text and associate an internal value (not displayed) to each item of the combobox
我有以下WPF組合框:
<ComboBox x:Name="MyComboBox"
Grid.Column="1"
SelectionChanged="MyComboBox_SelectionChanged">
<ComboBox.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel />
</ItemsPanelTemplate>
</ComboBox.ItemsPanel>
<ComboBoxItem Name="cbiEmployeeManagerType">
<StackPanel Orientation="Horizontal">
<Image Source="/Resources/Manager.png" />
<TextBlock Foreground="AliceBlue"
VerticalAlignment="Center">Manager</TextBlock>
</StackPanel>
</ComboBoxItem>
<ComboBoxItem Name="cbiEmployeeEngineerType">
<StackPanel Orientation="Horizontal">
<Image Source="/Resources/Engineer.png" />
<TextBlock Foreground="AliceBlue"
VerticalAlignment="Center">Engineer</TextBlock>
</StackPanel>
</ComboBoxItem>
</ComboBox>
第一個問題 :
在MyComboBox_SelectionChanged
我知道如何通過MyComboBox.SelectedIndex
檢測組合框中當前選擇的項目,但我不知道如何獲取顯示的文本以及在組合框中當前選擇的文本。 例如,如果我在組合框中選擇第二個項目,則想獲得“工程師”。 我該怎么做?
第二個問題 :
我也想做與組合框winforms相同的操作,在其中您可以顯示一個成員(winforms中combobox的DisplayMember
屬性),並在內部將其關聯到一個成員值(winforms中combobox的ValueMember
屬性),您可以在選擇時讀取該成員值組合框中的項目。 例如,假設以下combox項及其關聯值。
因此,“經理”和“工程師”將顯示在combox中,當我選擇“經理”時,我將獲得其關聯的值,即1000A,與工程師相同。 在WPF中可以嗎? 如果可以,怎么辦? 我已經讀過,可以使用DisplayMemberPath
和SelectedValuePath
組合框屬性,但是我不知道該怎么做。 我是否需要創建一個類並從那里填充組合,然后使用綁定? 任何代碼都將受到高度贊賞。
對於第一個問題,您可以通過以下代碼行來挖掘SelectionChanged
事件的SelectionChangedEventArgs e
,從而訪問ComboBoxItem的TextBlock:
private void MyComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var selectedItem = e.AddedItems[0] as ComboBoxItem;
var itemStackPanel = selectedItem.Contents as StackPanel;
// Get the TextBlock object from 'itemStackPanel' object
// TextBlock is with index 1 because it is defined second
// after Image inside the StackPanel in your XAML
var textBlock = itemStackPanel.Children[1] as TextBlock;
// This variable will hold 'Engineer' or 'Manager'
var selectedText = textBlock.Text;
}
或者您可以使用以下短行將以上所有代碼合並在一行中:( ?.
是C#6功能,以防萬一出現問題)
var selectedText = (((e.AddedItems[0] as ComboBoxItem)?.Content as StackPanel)?.Children[1] as TextBlock)?.Text;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.