开发者

WPF ListView selected item problem [duplicate]

This question already has answers here: 开发者_如何转开发 Selecting a Textbox Item in a Listbox does not change the selected item of the listbox (15 answers) Closed 2 years ago.

I have a ListView control with TextBox and Button inside the ListViewItem, my problem is that when you enter into a textbox the row doesn't select. If you want to select a row you have to click somewhere in the row where there is no control.

How can I make the row automaticly select when I click or enter into a child control of a row ?

I tried this on the button click event, but without any luck :

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

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

It always keep the first row selected.

Thank in advance.


try using attached properties

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;
    }

and heres its use

<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>

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜