WPF ListView selected item problem [duplicate]
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>
精彩评论