简体   繁体   中英

WPF C# Get text from a Textblock inside a ListBoxItem

How can i access a Textblock inside a Stackpanel that is inside a ListBoxItem?

For example:

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

Title.Text = "Item 1";

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

How can i later access the Text property of that Textblock with Listbox.SelectedItem?

Try this:

//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;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM