Reputation: 21999
Using MVVM:
<ListView ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem}" ... />
ViewModel:
public class Item: INotifyPropertyChanged { ... }
public ObservableCollection<Item> Items { get; set; }
public Item SelectedItem { get; set; }
Now if I change SelectedItem
// change
Items = new ObservableCollection<Item>(...);
SelectedItem = Items.FirstOrDefault(item => ... some condition);
// notify view
OnPropertyChanged();
OnPropertyChanged(nameof(SelectedItem));
Then wanted item become properly selected, but it's not focused. Using keyboard navigation if I give focus to ListView
somehow, then the very first item will become selected and focused.
How to give SelectedItem
focus?
Upvotes: 0
Views: 1720
Reputation: 5666
Personally I prefer to put my control's behavior logic inside the control's code. What I mean is to extend standard controls in order to change their behavior in the way I need.
First of all I need to extend the ListViewItem
control:
namespace Sample
{
public class ListViewItem : System.Windows.Controls.ListViewItem
{
protected override void OnSelected(RoutedEventArgs e)
{
base.OnSelected(e);
if (IsSelected)
{
Focus();
}
}
}
}
Then I need a ListView
control which uses my ListViewItem
:
namespace Sample
{
public class ListView : System.Windows.Controls.ListView
{
protected override DependencyObject GetContainerForItemOverride()
{
return new ListViewItem();
}
}
}
So my XAML will become:
<local:ListView ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem}" ... />
I hope it can help you.
Upvotes: 1
Reputation: 21999
One possibility is to automatically focus selected ListViewItem
when ListView
has focus.
xaml:
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<EventSetter Event="Selected" Handler="ListViewItem_Selected" />
</Style>
</ListView.ItemContainerStyle>
view cs:
void ListViewItem_Selected(object sender, RoutedEventArgs e)
{
if (listView.IsFocused)
(e.Source as ListViewItem)?.Focus();
}
Upvotes: 1