WPF ListView选择项目问题

时间:2010-12-14 13:27:29

标签: c# wpf listview select

我在ListViewItem中有一个带有TextBox和Button的ListView控件,我的问题是当你进入一个文本框时,该行不会选择。如果要选择一行,则必须单击无法控制的行中的某个位置。

如何在单击或输入行的子控件时自动选择行?

我在按钮点击事件上尝试了这个,但没有任何运气:

        DependencyObject dep = (DependencyObject)sender;
        while ((dep != null) && !(dep is ListViewItem))
        {
            dep = VisualTreeHelper.GetParent(dep);
        }

        if (dep != null)
        {
            lvRoutes.SelectedItem = (ListViewItem)dep;
        }

始终保持第一行的选择。

提前感谢。

2 个答案:

答案 0 :(得分:2)

答案 1 :(得分:0)

尝试使用附加属性

public static class ItemSelector
{
    public static DependencyProperty MakeSelectionProperty = 
        DependencyProperty.RegisterAttached("MakeSelection", 
        typeof(bool?), 
        typeof(ItemSelector), 
        new PropertyMetadata(null, OnMakeSelectionPropertyChanged));

    public static DependencyProperty ItemsControlProperty = 
        DependencyProperty.RegisterAttached("ItemsControl", 
        typeof(ItemsControl), 
        typeof(ItemSelector));

    public static void SetMakeSelection(
        DependencyObject d, bool value)
    {
        d.SetValue(MakeSelectionProperty, value);
    }

    public static void SetItemsControl(
        DependencyObject d, ItemsControl value)
    {
        d.SetValue(ItemsControlProperty, value);
    }

    private static void OnMakeSelectionPropertyChanged(
        DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var itemsControl = d.GetValue(ItemsControlProperty) 
            as ItemsControl;
        if (itemsControl == null)
            return;
        ((ListBoxItem) itemsControl.ContainerFromElement(d))
            .IsSelected = true;
    }

并且继续使用

<ListView ItemsSource="{Binding}" SelectionMode="Single">
<ListView.ItemTemplate>
  <DataTemplate>
    <TextBox Text="{Binding SomeText}" 
             w:ItemSelector.MakeSelection="{Binding RelativeSource=
                {RelativeSource Self}, Path=IsFocused}" 
             w:ItemSelector.ItemsControl="{Binding RelativeSource=
                {RelativeSource FindAncestor, AncestorType=
                    {x:Type ListView}}}" Margin="10" />
  </DataTemplate>
</ListView.ItemTemplate>