此代码生成一个Listview,其中包含一个网格,TextBox控件中有多个名称和电子邮件。我想知道如何在一行TextBox中捕获焦点事件,以便选择整个ListView行。
<ListView Name="lstRecipients" ItemsSource="{Binding Path=Recipients}">
<ListView.Resources>
<DataTemplate x:Key="tbNameTemplate">
<TextBox Name="tbName" Text="{Binding Path=Username, ValidatesOnDataErrors=True}"/>
</DataTemplate>
<DataTemplate x:Key="tbEmailTemplate">
<TextBox Name="tbEmail" Text="{Binding Path=Email, ValidatesOnDataErrors=True}"/>
</DataTemplate>
</ListView.Resources>
<ListView.View>
<GridView x:Name="gvRecipients">
<GridViewColumn Header="Name" CellTemplate="{StaticResource tbNameTemplate}"/>
<GridViewColumn Header="Email" CellTemplate="{StaticResource tbEmailTemplate}"/>
</GridView>
</ListView.View>
</ListView>
答案 0 :(得分:1)
您可以在TextBox上的GotFocus事件中添加一个处理程序,用于在ListView上设置所选项目。您可以使用ItemsControl.ContainerFromElement获取ListViewItem和ItemContainerGenerator.ItemFromContainer来获取绑定数据对象。在XAML中:
<TextBox GotFocus="tbName_GotFocus" Name="tbName" Text="{Binding Path=Username, ValidatesOnDataErrors=True}"/>
在代码隐藏中:
private void tbName_GotFocus(object sender, RoutedEventArgs e)
{
var container = lstRecipients.ContainerFromElement((DependencyObject)sender);
if (container != null)
{
lstRecipients.SelectedItem = lstRecipients.ItemContainerGenerator
.ItemFromContainer(container);
}
}
您还可以在ListView上设置处理程序,因为GotFocus是路由事件。您可以使用它来创建可在ListView之间共享的处理程序。在XAML中:
<ListView GotFocus="lstRecipients_GotFocus" Name="lstRecipients" ItemsSource="{Binding Path=Recipients}">
在代码隐藏中:
private void lstRecipients_GotFocus(object sender, RoutedEventArgs e)
{
var selector = sender as Selector;
if (selector != null)
{
var container = selector.ContainerFromElement
((DependencyObject)e.OriginalSource);
if (container != null)
{
selector.SelectedItem = selector.ItemContainerGenerator
.ItemFromContainer(container);
}
}
}
(如果你不想让TextBox完全可编辑,你也可以设置Focusable="False"
或使用TextBlock而不是TextBox,焦点会转到ListView并在单元格中选择行点击了。)