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

4
我已为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呢?
非常感谢!

你是在尝试将“textbox”用作“lable”吗? - Rev
我可以这样做,但是我希望内容可以直接更新。我在combobox上也遇到了同样的问题。 - Archedius
1个回答

7

可以在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>

请提供需要翻译的内容,谢谢!

请注意,它会改变ListView的行为:当ListView失去焦点时,所选项目将丢失。到目前为止,我找到的唯一解决方案是:https://dev59.com/qXRB5IYBdhLWcg3wWF8H#863167 - Welcor

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接