[英]Obtain value from ListBox containing TextBlocks using SelectedItem in WPF
我有一個列表框,其數據來自linq查詢的結果。 列表框正確顯示了所有內容,但我無法弄清楚如何從列表框中提取所選項目。 我已經嘗試了一些方法,但我要么得到異常的提示,說它不能轉換匿名類型,要么值不能將其值保留到下一行。
數據源
private void FavoritesPopulate()
{
dynamic qryFavorties = (from db in AppGlobal.GlobalDataset.Tables[ListFavorites.ListStringName].AsEnumerable()
select new { Name = db.Field<string>("SystemName") }).OrderBy(db => db.Name);
this.lbSystems.DataContext = qryFavorties;
}
列表框
<ListBox x:Name="lbSystems" VerticalAlignment="Stretch" DockPanel.Dock="Left" Width="Auto" IsTextSearchEnabled="True" TextSearch.TextPath="Name"
Background="Transparent" Foreground="{DynamicResource DynamicFrmFG}" FontFamily="Consolas"
ItemsSource="{Binding}" ItemTemplate="{StaticResource mySystemTemplate}" SelectionChanged="lbSystems_SelectionChanged" >
<ListBox.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="{DynamicResource DynamicCtrlHighlight}"/>
<SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="{DynamicResource DynamicCtrlHighlight}"/>
</ListBox.Resources>
</ListBox>
資源
<Window.Resources>
<BooleanToVisibilityConverter x:Key="BoolToVis" />
<DataTemplate x:Key="mySystemTemplate">
<StackPanel>
<TextBlock Text="{Binding Path=Name}" Foreground="{DynamicResource DynamicFrmFG}" FontSize="14" FontFamily="Consolas" />
</StackPanel>
</DataTemplate>
</Window.Resources>
我嘗試獲取所選系統名稱的代碼
ListBoxItem myListBoxItem = (ListBoxItem)(this.lbSystems.ItemContainerGenerator.ContainerFromItem(this.lbSystems.Items.CurrentItem));
TextBlock tb = (TextBlock)this.lbSystems.SelectedItem;
ListBoxItem lbi = (this.lbSystems.SelectedItem as ListBoxItem);
ListItemCollection lbi = this.lbSystems.SelectedItem as ListItemCollection;
var test = lbi.Content.ToString();
當我查看IDE時,嘗試執行的大多數操作在“監視”屏幕中都有變量表示它們在當前上下文中不存在。 然后,強制轉換TextBlock引發錯誤:
Unable to cast object of type '<>f__AnonymousType0`1[System.String]' to type 'System.Windows.COntrols.TextBlock'
誰能告訴我嘗試檢索所選項目時我做錯了什么,或者如果我將數據綁定錯誤,這就是為什么我無法獲取所選項目的原因。
編輯:應用解決方案后,我確實必須對列表框進行另一次編輯才能使其再次可搜索。
以前的代碼
IsTextSearchEnabled="True" TextSearch.TextPath="Name"
修復代碼
IsTextSearchEnabled="True" TextSearch.TextPath="{Binding Name}"
您無需使用select new { Name = db.Field<string>("SystemName") }
行創建匿名類型。 只需使用select db.Field<string>
選擇一個普通的舊字符串select db.Field<string>
:
IEnumerable<string> qryFavorties = (from db in AppGlobal.GlobalDataset.Tables[ListFavorites.ListStringName].AsEnumerable()
select db.Field<string>("SystemName")).OrderBy(name => name);
this.lbSystems.DataContext = qryFavorties;
然后當然綁定到(string)項目本身:
<TextBlock Text="{Binding}" ... />
現在, ListBox.SelectedItem
應該是一個字符串,您可以通過取消裝箱將其換成一行:
string selectedValue = (string)this.lbSystems.SelectedItem;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.