获取ListViewItem子项

时间:2013-12-19 14:54:00

标签: c# wpf

<ListView x:Name="lvPayload" Grid.Row="1" ItemsSource="{Binding Payload}" HorizontalAlignment="Center" VerticalAlignment="Center">
    <ListView.ItemTemplate>
        <DataTemplate>
            <TextBox Text="{Binding Value, StringFormat=0x{0:x2}, Mode=OneWay, Converter={StaticResource hexConverter}}" FontSize="15" Margin="2,1,2,1" MinWidth="25" MinHeight="20" VerticalAlignment="Center" HorizontalAlignment="Center"/>
        </DataTemplate>
    </ListView.ItemTemplate>
    <ListView.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel Orientation="Horizontal" VerticalAlignment="Center"/>
        </ItemsPanelTemplate>
    </ListView.ItemsPanel>
</ListView>

我使用以下行获取每个ListViewItem

ListViewItem lvi = lvPayload.ItemContainerGenerator.ContainerFromIndex(0) as ListViewItem;

有没有办法到达TextBox控件并获取其Text属性?

迈克尔给了我回复:

这是FindVisualChild方法:

public static T FindVisualChild<T>(DependencyObject depObj) where T : DependencyObject
{
    if (depObj != null)
    {
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
            if (child != null && child is T)
            {
                return (T)child;
            }

            T childItem = FindVisualChild<T>(child);
            if (childItem != null) return childItem;
        }
    }
    return null;
}

获取TextBox的代码:

ListViewItem lvi = lvPayload.ItemContainerGenerator.ContainerFromIndex(0) as ListViewItem;
// Getting the ContentPresenter of lvi
var cp = FindVisualChild<ContentPresenter>(lvi);

// Finding textBlock from the DataTemplate that is set on that ContentPresenter
var dtmpl = cp.ContentTemplate as DataTemplate;
var tb = (TextBox)dtmpl.FindName("myTb", cp);

1 个答案:

答案 0 :(得分:1)

是的,但首先您需要为其提供Name属性。给它一个名字后你可以这样做:

// Getting the ContentPresenter of lvi
var cp = FindVisualChild<ContentPresenter>(lvi);

// Finding textBlock from the DataTemplate that is set on that ContentPresenter
var dt = cp.ContentTemplate as DataTemplate;
var tb = (TextBox)dt.FindName("{name}", cp);