WPF M-V-VM List View

  • Thread starter Thread starter Mike B
  • Start date Start date
M

Mike B

Hello all, I am new to WPF and MVVM and am having a heck of a time trying to
get a value in a list view. I have everything working where my ViewModel
page gets the notification that the selection changed, however, my
collection views "CurrentItem" property is never updated. Does anyone have
any example on how they accomplished this? Below is what most of my code
looks like.....

Currently, I have a list view that looks like this:


<ListView ItemsSource="{Binding Path=Vehicles,Mode=TwoWay}"
local:SelectionBehavior.SelectionChanged="{Binding SelectVehicleCommand}">
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="HorizontalContentAlignment"
Value="Stretch" />
</Style>
</ListView.ItemContainerStyle>
<ListView.View>
<GridView>
<GridViewColumn Header="Vehicle ID"
DisplayMemberBinding="{Binding Path=VehicleID}" />
<GridViewColumn Header="Description"
DisplayMemberBinding="{Binding Path=Description}" />
</GridView>

</ListView.View>
</ListView>





My ViewModel page looks something like this:






private Vehicle _currentVehicle;
private CollectionView _vehicles;


public VehiclePageViewModel()
{
Vehicles = new CollectionView(Globals.entityManager.Vehicles.Where(e =>
e.isActive == true));
CurrentVehicle = (Vehicle)Vehicles.CurrentItem;
this.SelectVehicleCommand = new DelegateCommand(o =>
this.HandleCurrentVehicleChanged(SelectVehicleCommand),
o => true,
null);
}


public Vehicle CurrentVehicle
{
get
{
return _currentVehicle;
}
set { _currentVehicle = value; }
}

public CollectionView Vehicles
{
get
{
return _vehicles;
}
set { _vehicles = value; }
}





public DelegateCommand SelectVehicleCommand { get; private set; }

private void HandleCurrentVehicleChanged(object sender)
{
CurrentVehicle = (Vehicle)Vehicles.CurrentItem;
if (CurrentVehicle != null)
{
OnPropertyChanged("CurrentVehicle");
}
}


TIA
Mike
 
In case anyone else is new to the MVVM ideas, what fixed it was adding
IsSynchronizedWithCurrentItem="True" to the listview.

<ListView ItemsSource="{Binding Path=Vehicles,Mode=TwoWay}"
local:SelectionBehavior.SelectionChanged="{Binding SelectVehicleCommand}"
IsSynchronizedWithCurrentItem="True">
 
Back
Top