如何从列表框中的选定 TextBlock 元素中提取值? [英] How to extract value from selected TextBlock element in a ListBox?

查看:15
本文介绍了如何从列表框中的选定 TextBlock 元素中提取值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 ListBox 来显示包含在 Dictionary<> 对象中的所有值:

I'm using a ListBox to display all values contained in Dictionary<> object:

<ListBox Height="519" x:Name="ContactsListBox" Width="460" Margin="0,0,0,0" SelectionChanged="ContactsListBox_SelectionChanged">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Vertical">
                    <TextBlock Text="{Binding Key}" Margin="5" Foreground="{StaticResource PhoneAccentBrush}"/>
                    <TextBlock x:Name ="LastNameData" Text="{Binding Value}" Margin="20, 0" />
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
</ListBox>

内容由以下代码填充:

Dictionary<long, Contact> contacts = new Dictionary<long, Contact>();
this.ContactsListBox.ItemsSource = contacts;

现在,我想通过知道其 Key 或仅通过从LastNameData"TextBlock 中提取值来知道"当前选择了 ListBox 中的哪个Contact".

Now, I would like to 'know' which specific "Contact" in ListBox is currently selected, either by knowing its Key, or just by extracting value from "LastNameData" TextBlock.

我尝试做类似的事情,但显然它不起作用:

I tried doing something like that, but obviosly it doesn't work:

private void ContactsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    ListBox lb = this.ContactsListBox.SelectedItem as ListBox;
    this.Test_SomeOtherTextBlock.Text = lb.ToString();
}

非常感谢您的帮助!

推荐答案

有几个问题:

在 Xaml 中你可能不想显示类名,而是一个合理的字符串,例如:

In Xaml you probably don't want to display the class name, but a reasonable string, for example:

<TextBlock x:Name ="LastNameData" Text="{Binding Value.LastName}" Margin="20, 0" />

在选择处理中,选择的项目是KeyValuePair<...>.如果您在调试器中查看返回的类型,您可以很容易地自己找到它.(应该是程序员的一种反射,因此永远不会出现上述问题:))

In the selection processing the selected item is KeyValuePair<...>. You could easily find it yourself, if you looked at the returned type in debugger. (Should be kind of a reflex for a programmer, hence a questions like above should never appear :))

private void ContactsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { 
    KeyValuePair<long, Contact> kv = (KeyValuePair<long, Contact>)this.ContactsListBox.SelectedItem;
    Contact c = (Contact)kv.Value;
    Debug.WriteLine(c.LastName);
}

这篇关于如何从列表框中的选定 TextBlock 元素中提取值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆