WPF C#从ListBoxItem中的Textblock获取文本

时间:2017-07-03 13:47:31

标签: c# wpf xaml listbox textblock

如何访问ListBoxItem内的Stackpanel内的Textblock?

例如:

ListBoxItem MyItem = new ListBoxItem();
StackPanel StackPnl = new StackPanel();
TextBlock Title = new TextBlock();

Title.Text = "Item 1";

StackPnl.Children.Add(Title);
MyItem.Content = StackPnl;

我如何以后使用Listbox.SelectedItem访问该Textblock的Text属性?

1 个答案:

答案 0 :(得分:1)

试试这个:

//listBox1 is your ListBox
ListBoxItem MyItem = listBox1.SelectedItem as ListBoxItem;
if(MyItem != null)
{
    StackPanel sp = MyItem.Content as StackPanel;
    if(sp != null && sp.Children.Count > 0)
    {
        TextBlock textBlock = sp.Children[0] as TextBlock;
        if(textBlock != null)
        {
            string text = textBlock.Text;
        }
    }
}