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