Reputation: 273
I have a ControlTemplate to show Items in ListView. ListView is having 500+ items. I am preserving the state and getting selected item from XML and sending it to listview to select it by default for next navigation to the screen.
My problem is How can I set selected item (which may be present in last i.e. out of view) by xaml. ViewModel doesn't know about any UI control, so I cant apply ScrollIntoView method in ViewModel.
Can I use any Setter or Style to do this?
Please suggest.
Upvotes: 0
Views: 1476
Reputation: 1251
I've recently done this with a DataGrid. The trick is to attach a custom Behavior to your View. Like that.
<ListView ... >
<iy:Interaction.Behaviors>
<ext:ScrollIntoViewBehavior />
</iy:Interaction.Behaviors>
...
</ListView>
And the assocciated class:
public class ScrollIntoViewBehavior : Behavior<ListView>
{
protected override void OnAttached()
{
base.OnAttached();
this.AssociatedObject.SelectionChanged += new SelectionChangedEventHandler(AssociatedObject_SelectionChanged);
}
protected override void OnDetaching()
{
base.OnDetaching();
this.AssociatedObject.SelectionChanged -= new SelectionChangedEventHandler(AssociatedObject_SelectionChanged);
}
private void AssociatedObject_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (sender is ListView)
{
ListView grid = (sender as ListView);
if (grid.SelectedItem != null)
{
grid.Dispatcher.BeginInvoke(() =>
{
grid.UpdateLayout();
grid.ScrollIntoView(grid.SelectedItem);
});
}
}
}
}
Some things to be aware of:
Upvotes: 1