开发者

retrieving the content properties from data template in wpf

I have a particular template for a listbox item which contains different textblocks. After adding the items in the listbox I want to retrieve the text of a particular textblock of a particular listbox item. How can I do that?

 <ListBox x:Name="listBox1" Grid.Row="0" SelectionChanged="listBox1_SelectionChanged">             
            <ListBox.ItemTemplate>
                <DataTemplate>
                  开发者_StackOverflow中文版  <StackPanel Orientation="Horizontal"  Margin="0,2,0,0">
                        <CheckBox Name="cbSelect" VerticalAlignment="Center" Visibility="{Binding isVisible}"/>                                                            
                        <StackPanel Orientation="Vertical">
                            <Grid HorizontalAlignment="Stretch" >
                                <TextBlock Name="txtTitle" VerticalAlignment="Bottom"  Text="{Binding Title}"  Style="{StaticResource PhoneTextExtraLargeStyle}"/>
                                <TextBlock Name="txtDate" Foreground="{StaticResource PhoneInverseInactiveBrush}"  HorizontalAlignment="Right" VerticalAlignment="Center" Text="{Binding CreatedOn}" Margin="0,0,30,0" Style="{StaticResource PhoneTextSmallStyle}" />
                          <!--  <Image x:Name="lineImg" Source="/Icons/appbar.next.rest.png" HorizontalAlignment="Right"  VerticalAlignment="Bottom" Width="48" Height="48"/>-->
                            </Grid>
                            <TextBlock Name="txtContent"  Foreground="{StaticResource PhoneDisabledBrush}" VerticalAlignment="Bottom" Text="{Binding Content}" Style="{StaticResource PhoneTextNormalStyle}" />                            
                            <Line Stroke="{StaticResource PhoneBorderBrush}"  StrokeThickness=" 2" X1="0" Y1="0" X2="{Binding ElementName=listBox1, Path=ActualWidth}" Y2="0" Margin="0,6,0,0" ></Line>
                        <!--   <Image x:Name="lineImg" Source="/Icons/Line.png" HorizontalAlignment="Center" Width="500" Height="2" Margin="0,15,0,0" />-->
                        </StackPanel>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

In the above code, after adding the items to the listbox, I want the text of txtTitle of a particular item. How can I get it?


You need to get a reference to the ContentPresenter of the item.

ListBoxItem myListBoxItem = (ListBoxItem)(myListBox.ItemContainerGenerator.ContainerFromItem(myListBox.Items.CurrentItem));
ContentPresenter myContentPresenter = FindVisualChild<ContentPresenter>(myListBoxItem);
DataTemplate myDataTemplate = myContentPresenter.ContentTemplate;
TextBlock myTextBlock = (TextBlock)myDataTemplate.FindName("textBlock", myContentPresenter);

The FindVisualChild method along with the full example can be found here.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜