【问题标题】:retrieving the content properties from data template in wpf从 wpf 中的数据模板中检索内容属性
【发布时间】:2011-05-30 12:26:57
【问题描述】:

我有一个包含不同文本块的列表框项目的特定模板。在列表框中添加项目后,我想检索特定列表框项目的特定文本块的文本。我该怎么做?

 <ListBox x:Name="listBox1" Grid.Row="0" SelectionChanged="listBox1_SelectionChanged">             
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <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>

在上面的代码中,将项目添加到列表框后,我想要特定项目的 txtTitle 的文本。我怎样才能得到它?

【问题讨论】:

    标签: wpf data-binding binding datatemplate


    【解决方案1】:

    您需要获得对该项目的ContentPresenter 的引用。

    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);
    

    FindVisualChild 方法以及完整示例可以在 here 找到。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多