充分利用绑定列表框选择的项目字符串 [英] Getting selected item string from bound ListBox

查看:102
本文介绍了充分利用绑定列表框选择的项目字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在与从绑定的文本块得到一个列表框在一个字符串中的一个问题,当我使用下面的代码,我可以绑定列表框和列表框有项目显示出来,但被点击列表中的项目时我没有得到正确的琴弦,我打印一个消息框,对象名称的消息,如

I'm having a problem with getting a string from a bound textblock within a listbox, when I use the code below, I can bind the listbox and the listbox has items showing up, but when the item in the list is clicked I don't get the proper string, I print a message box a message with objects names like

MyApp.Item

而不是显示出来。 myApp为应用程序的名称和项目是我的模型,我绑定到列表框中的名称。从所选项目的文本正确露面时,列表框不绑定。

shows up instead. myApp is the name of the app and Item is the name of my model that I am binding to the listbox. The proper text from the selected item showed up when the listbox was not binded.

private void listBoxtrend_Tap(object sender, GestureEventArgs e)
{
    selectedText = "";

    selectedText = listBox.SelectedValue.ToString();

    MessageBox.Show(selectedText);
}



XML

xml

<ListBox ItemsSource="{Binding Item}" Foreground="RoyalBlue" 
    Height="395" HorizontalAlignment="Center" 
    Margin="12,111,0,0" Name="listBox" 
    VerticalAlignment="Top" Width="438"
    TabIndex="10"  Tap="listBox_Tap" >
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock TextWrapping="Wrap" FontSize="26" HorizontalAlignment="Left"
                Name="tblItem" Text="{Binding ItemString}"
                VerticalAlignment="Top" />
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>



我会很感激,如果你能帮助我谢谢

I'd really appreciate if you could help me thanks

推荐答案

您要绑定到ItemString在DataTemplate中的TextBlock中,并在ListView项集合。这样的SelectedValue的将是项目类型。你实际上应该做在你的点击处理这样的事情来获得在ItemString的价值...

You're binding to the ItemString in the DataTemplate's TextBlock and the Item Collection in the ListView. As such the SelectedValue will be of the Item type. You should actually be doing something like this in your Tap handler to get at the ItemString's value...

private void listBoxtrend_Tap(object sender, GestureEventArgs e)
{
    selectedText = "";

    var selected = listBox.SelectedValue as Item;
    selectedText = selected.ItemString;

    MessageBox.Show(selectedText);
}

在您的例子中,的ToString 正在打印类的名称。您也可以重写的ToString在你的项目模型,你想要的字符串是什么

In your example, the ToString is printing the name of the class. You could also override ToString in your Item model to be whatever you want the string to be.

注:种类和可能有点过,我猜了一下基于断你在你的问题中写道。此外,也没有必要selectedText设置为将只是在第三行上述覆盖一个空串。我想保持它,你可以得到什么,我在你的代码改变了一些想法。

Note: the types and such may be a bit off, I guessed a bit based off of what you wrote in your question. Also, there is no need to set selectedText to an empty string that will just be overwritten in the third line above. I wanted to keep it so you could get some idea of what I changed in your code.

这篇关于充分利用绑定列表框选择的项目字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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