[英]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.