ListView中使用DataTemplete

xaml:

<Window.Resources>
<c:ArrayList x:Key="stuList">
<local:Student Name="张三" Age="20" Skill="三年级" />
<local:Student Name="李四" Age="21" Skill="二年级" />
<local:Student Name="王五" Age="23" Skill="三年级" />
<local:Student Name="王二" Age="26" Skill="五年级" />
<local:Student Name="Tom" Age="15" Skill="一年级" />
</c:ArrayList>
<DataTemplate x:Key="NameDT">
<TextBox x:Name="tName" Text="{Binding Name}" GotFocus="tName_GotFocus"></TextBox>
</DataTemplate>
<DataTemplate x:Key="AgeDT">
<TextBlock x:Name="tAge" Text="{Binding Age}"></TextBlock>
</DataTemplate>
<DataTemplate x:Key="SkillDT">
<TextBlock x:Name="tSkill" Text="{Binding Skill}">
</TextBlock>
</DataTemplate>
</Window.Resources>
<Grid>
<ListView x:Name="listV" ItemsSource="{StaticResource stuList}">
<ListView.View>
<GridView>
<GridViewColumn Header="Name" CellTemplate="{StaticResource NameDT}" />
<GridViewColumn Header="Age" CellTemplate="{StaticResource AgeDT}" />
<GridViewColumn Header="Skill" CellTemplate="{StaticResource SkillDT}" />
</GridView>
</ListView.View>
</ListView>
</Grid>

 

C#: 代码

/// Window2.xaml 的交互逻辑
/// </summary>
public partial class Window2 : Window
{
public Window2()
{
InitializeComponent();
}

private void tName_GotFocus(object sender, RoutedEventArgs e)
{
//访问业务逻辑数据
TextBox tb = e.OriginalSource as TextBox;//获取事件的发起源头
ContentPresenter cp = tb.TemplatedParent as ContentPresenter;//获取模板目标
Student stu = cp.Content as Student;//获取业务逻辑数据
this.listV.SelectedItem = stu;//设置选中项

//访问界面元素
ListViewItem lvl = listV.ItemContainerGenerator.ContainerFromItem(stu) as ListViewItem;
TextBox tbView = FindVisualChild<TextBox>(lvl);
MessageBox.Show(tbView.Text);
}
//寻找元素
public TextBox FindVisualChild<TextBox>(DependencyObject obj) where TextBox : DependencyObject
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
DependencyObject dobj = VisualTreeHelper.GetChild(obj, i);//返回子元素
if (dobj != null && dobj is TextBox)
{
return dobj as TextBox;
}
else
{
TextBox t = FindVisualChild<TextBox>(dobj);
if (t != null)
{
return t;
}
}
}
return null;
}
}

public class Student
{
public string Name { get; set; }
public int Age { get; set; }
public string Skill { get; set; }
}

posted @ 2013-12-03 18:19  木子羊羽  阅读(489)  评论(0编辑  收藏  举报