通过单击ListViewItem的DataTemplate中的控件来选择它

本文关键字:控件 选择 DataTemplate 单击 ListViewItem | 更新日期: 2023-09-27 17:58:38

我为ListView中的项编写了一个自定义DataTemplate,类似于以下内容:

 <DataTemplate x:Key="CustomerStateTemplate">
    <Grid Margin="5, 5, 5, 5">
        <Grid.ColumnDefinitions>
            ...
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            ...
        </Grid.RowDefinitions>
        <Image Grid.Row="0" Grid.RowSpan="2" Width="24" Height="20" ... />
        <TextBox Style="{StaticResource CustomerStyle}" Grid.Column="0" 
                       Grid.Row="0" Grid.ColumnSpan="2"
                       Name="nameField">
            <TextBox.Text>
                <Binding Path="Name" />
            </TextBox.Text>
        </TextBox>
        ...

我获得了我美丽的风格。现在,如果我想选择项目,我必须单击模板控件之间的空白处。如果我点击ListViewItem中的文本框,它将不会像项目一样选择。那么,有没有一种方法可以通过单击ListViewItem模板中的控件来选择它?

万分感谢!

通过单击ListViewItem的DataTemplate中的控件来选择它

可以在ListViewItem上添加一个触发器,该触发器始终选择项目,然后键盘焦点位于项目内部。当您在ListViewItem上执行此操作时,DataTemplate中的所有控件都有相同的行为,这应该是您的解决方案。。。

示例:

<Page
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:sys="clr-namespace:System;assembly=mscorlib">
  <Grid>
  <Grid.Resources>
    <x:Array x:Key="Data" Type="{x:Type sys:String}">
      <sys:String>first</sys:String>
      <sys:String>second</sys:String>
      <sys:String>third</sys:String>
    </x:Array>
  <Style TargetType="ListViewItem" x:Key="itemStyle">
    <Style.Triggers>
      <Trigger Property="IsKeyboardFocusWithin" Value="True">
        <Setter Property="IsSelected" Value="True" />
      </Trigger>
    </Style.Triggers>
  </Style>
  </Grid.Resources>

  <ListView ItemsSource="{StaticResource Data}" ItemContainerStyle="{StaticResource itemStyle}">
    <ListView.ItemTemplate>
      <DataTemplate DataType="{x:Type sys:String}">
        <TextBox Text="{Binding .}">
        </TextBox>
      </DataTemplate>
    </ListView.ItemTemplate>
  </ListView>
  </Grid>
</Page>

我希望它清楚。。。