【问题标题】:Select a ListViewItem by clicking on the controls in its DataTemplate通过单击其 DataTemplate 中的控件来选择 ListViewItem
【发布时间】:2011-09-09 23:34:22
【问题描述】:

我为 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吗?
  • 可以,但我希望直接更新内容。我对组合框也有同样的问题

标签: c# .net wpf wpf-controls datatemplate


【解决方案1】:

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

我希望它清楚...

【讨论】:

  • 小心,它改变了列表视图的行为:当列表视图失去焦点时,选定的项目将丢失。到目前为止我找到的唯一解决方案:stackoverflow.com/a/863167/4394435
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-30
  • 2013-12-31
  • 2016-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多