To pin the selected ListView element inside the button you clicked, you can use the MVVM template. In my ListView, in XAML, I bind ItemsSource and SelectedItem to the ViewModel class. I also bind my Command button in the template to RunCommand in the ViewModel.
The hard part gets the binding right from the template to the active DataContext.
Once you do this, you can capture the SelectedCustomer inside the RunCommand, which runs when the button is clicked.
I have included a piece of code to help you get started. You can find implementations of ViewModelBase and DelegateCommand through Google.
Here is the XAML:
<Window x:Class="ListViewScrollPosition.Views.MainView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Main Window" Height="400" Width="400"> <Grid> <ListView ItemsSource="{Binding Path=Customers}" SelectedItem="{Binding Path=SelectedCustomer}" Width="Auto"> <ListView.View> <GridView> <GridViewColumn Header="First Name"> <GridViewColumn.CellTemplate> <DataTemplate> <StackPanel Margin="6,2,6,2"> <TextBlock Text="{Binding FirstName}"/> </StackPanel> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> <GridViewColumn Header="Last Name"> <GridViewColumn.CellTemplate> <DataTemplate> <StackPanel Margin="6,2,6,2"> <TextBlock Text="{Binding LastName}"/> </StackPanel> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> <GridViewColumn Header="Address"> <GridViewColumn.CellTemplate> <DataTemplate> <StackPanel Margin="6,2,6,2"> <Button Content="Address" Command="{Binding Path=DataContext.RunCommand, RelativeSource= {RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}}"/> </StackPanel> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> </GridView> </ListView.View> </ListView> </Grid> </Window>
Here is the ViewModel model:
using System.Collections.ObjectModel; using System.Windows.Input; using ListViewScrollPosition.Commands; using ListViewScrollPosition.Models; namespace ListViewScrollPosition.ViewModels { public class MainViewModel : ViewModelBase { public ICommand RunCommand { get; private set; } public MainViewModel() { RunCommand = new DelegateCommand<object>(OnRunCommand, CanRunCommand); _customers = Customer.GetSampleCustomerList(); _selectedCustomer = _customers[0]; } private ObservableCollection<Customer> _customers = new ObservableCollection<Customer>(); public ObservableCollection<Customer> Customers { get { return _customers; } } private Customer _selectedCustomer; public Customer SelectedCustomer { get { return _selectedCustomer; } set { _selectedCustomer = value; OnPropertyChanged("SelectedCustomer"); } } private void OnRunCommand(object obj) {
Here I am linking in ViewModel with a view:
public partial class MainView : Window { public MainView() { InitializeComponent(); DataContext = new ViewModels.MainViewModel(); } }
Zamboni
source share