开发者

wpf access lisbox selected item if it isn't string

I have a listbox which displays Name property from an array of Movie objects

<ListBox Name="listBox1" SelectionChanged="listBox1_SelectionChanged">
                   开发者_如何学C  <ItemsControl ItemsSource="{Binding}" >
                          <ItemsControl.ItemTemplate >
                              <DataTemplate >                                      
                                     <TextBlock Name="textBlock1" Text="{Binding Name}"/> 
                              </DataTemplate>
                          </ItemsControl.ItemTemplate>
                     </ItemsControl>
                 </ListBox>

How can I access the text of the textBlock that's inside the ListBox in Code?

I must use the value of the Name property in my code


The selected item reported by the listbox exposes you the object that owns the Name property bound in the TextBlock. At this point the game is over.


When you do the above every textblock inside the itemscontrol has a name textblock1 that too with a scope limited to each item container.

If you want each of those textblocks individually, I usually do something like:

<TextBlock Text="{Binding Name}" Loaded="TextBlock_Loaded"/>

And in the code register those textboxes in whatever way you wish. A list probably,

List<TextBlock> TextBlockList = new List<TextBlock>();

private void TextBlock_Loaded(object sender, RoutedEventArgs e)
        {
            TextBlockList.Add((TextBlock)sender);           
        }

And for example, access the stuff as:

String FirstItem = TextBlockList.ElementAt(0).Text;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜