[英]WPF MVVM: Returning selected ListBox item on User Control back to ViewModel
[英]wpf ListBox Control: simple GetSelectedValue / item-value
列表框不只綁定組合框而綁定(公開值)
Xaml
<ListBox SelectionChanged="LBX_AddTaskOptions_SelectionChanged" HorizontalAlignment="Left" Margin="19,29,0,0" Name="LBX_AddTaskOptions" VerticalAlignment="Top" Width="125" FontWeight="Bold" Background="Beige">
<ListBoxItem Background="Beige" FontWeight="Bold" v>
<StackPanel Orientation="Horizontal">
<TextBlock Text="internet"></TextBlock>
<Image Source="Images\IE_BlackRed.png" Height="30"></Image>
</StackPanel>
</ListBoxItem>
<ListBoxItem Background="Beige" FontWeight="Bold">
<StackPanel Orientation="Horizontal">
<TextBlock Text="localFolder"></TextBlock>
<Image Source="Images\Folder_Black.png" Height="30"></Image>
</StackPanel>
</ListBoxItem>
</ListBox>
代碼背后
private void LBX_AddTaskOptions_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var SelItm = LBX_AddTaskOptions.SelectedItem.ToString();
MessageBox.Show(Sel);
}
我一直在搜索該問題,盡管答案僅是針對復雜的問題,因為我是.net Developer,但我知道所有提取DDL文本/值的方法,甚至都做了擴展,雖然無法弄清楚如何進行這種簡單的值提取
不應該很簡單嗎?
messageBox顯示控件的名稱(:
對於XAML,這不是正確的方法。 您不想列出每個項目的標記,而是使用ItemTemplate
定義其外觀,並使用綁定來呈現實際項目:
<ListBox SelectionChanged="LBX_AddTaskOptions_SelectionChanged" Name="LBX_AddTaskOptions">
<ListBox.ItemTemplate>
<ListBoxItem Background="Beige" FontWeight="Bold" v>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding}" />
<Image Source="Images\IE_BlackRed.png" Height="30" />
</StackPanel>
</ListBoxItem>
</ListBox.ItemTemplate>
</ListBox>
將ListBox ItemsSource
綁定到模型數據本身(即,在這種情況下為字符串數組)。 現在,最終您可能會想要使用視圖模型,但是您也可以在加載后從代碼中添加項目:
string[] ListBoxItems = new string[] { "internet", "local folder" };
LBX_AddTaskOptions.ItemsSource = ListBoxItems;
這應該導致SelectedValue
給您正確的值。
腳注 -您可以使用在問題中寫出的標記來獲得選定的值-但這很丑陋,並且會破壞XAML的全部目的。 您需要將SelectedItem
轉換為ListBoxItem
,然后獲取其子項並將其轉換為StackPanel,並獲取其子項,依此類推。 然后,當然,如果標記發生更改,那么您剛才編寫的代碼將不再有效。
您所選擇的值中獲得的項目是一個內部帶有控件的ListBoxItem。 如果要提取文本等值,則必須執行此操作
private void LBX_AddTaskOptions_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var SelItm = LBX_AddTaskOptions.SelectedItem as ListBoxItem;
var StackPanel = SelItm.Content as StackPanel;
foreach (var child in StackPanel.Children)
{
if(child is TextBlock)
{
MessageBox.Show((child as TextBlock).Text);
}
}
}
您必須對控件進行某種程度的挖掘才能獲得實際的文本。 有很多獲取價值的方法,但這是非常基本的方法。
調用ToString()方法只會將當前對象轉換為一個字符串,即ListBoxItem。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.