【问题标题】:Setting SelectedItem in ListView when user clicks in ItemTemplate Textbox当用户在 ItemTemplate 文本框中单击时在 ListView 中设置 SelectedItem
【发布时间】:2013-06-07 15:31:25
【问题描述】:

我有以下 ListView(简化版):

<ListView Name="lvwNotes" KeyUp="lvwNotes_KeyUp">
    <ListView.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Vertical">
                <DockPanel Background="LightGray">
                     <TextBlock DockPanel.Dock="Right" Text="{Binding Path=Author}" />
                     <TextBlock Text="{Binding Path=Timestamp}" />
                </DockPanel>
                <TextBox Text="{Binding Path=Text}" 
                         GotFocus = "lvwNotes_TextBox_GotFocus"
                         TextWrapping="Wrap" />
            </StackPanel>
        </DataTemplate>
    </ListView.ItemTemplate>

通过单击更改所选项目仅在用户单击带有 TextBlock 的 DockPanel 时有效,但在单击 TextBox 时无效。我想要实现的是将所选项目设置为包含用户单击的 TextBox 的项目。

我设法打通了与 TextBox 相关的 ListViewItem:

private void lvwNotes_TextBox_GotFocus(object sender, RoutedEventArgs e) {
    DependencyObject o = Tools.GetAncestorByType((DependencyObject)sender, typeof(ListViewItem));
    if (!o.Equals(null)) {
        // code to select this ListViewItem
    }
}

但是设置

lvwNotes.SelectedIten = o ;

仍然无效。我也尝试过使用 Dispatcher.BeginInvoke 的一些技巧,但老实说,我并不完全知道自己在做什么。

【问题讨论】:

    标签: wpf listview textbox selecteditem itemtemplate


    【解决方案1】:

    将此添加到您的代码中

    <ListView.Resources>
        <Style TargetType="ListViewItem">
            <Style.Triggers>
                <Trigger Property="IsKeyboardFocusWithin" Value="True">
                    <Setter Property="IsSelected" Value="True" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </ListView.Resources>
    

    【讨论】:

    • 您甚至可以删除 GotFocus 的事件处理程序。
    【解决方案2】:

    除非在DataTemplate 中明确更改,否则DataContext 是当前项,因此:

    private void lvwNotes_TextBox_GotFocus(object sender, RoutedEventArgs e)
    {
        var tb = (TextBox)sender;
        lvwNotes.SelectedItem = tb.DataContext;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-20
      • 2012-03-26
      • 2020-03-31
      • 2014-11-11
      • 2021-09-12
      相关资源
      最近更新 更多