views:

537

answers:

1

I've been banging my head against the wall for a couple of days on this and it's time to ask for help.

I've got a DataGrid and DataForm on the same UserControl. I'm using an MVVM approach so there is a single ViewModel for the UserControl. That ViewModel has a couple of properties that are relevant to this discussion:

public ObservableCollection<VehicleViewModel> Vehicles { get; private set; }
public VehicleViewModel SelectedVehicle
{
    get { return selectedVehicle; }
    private set
    {
        selectedVehicle = value;
        OnPropertyChanged( "SelectedVehicle" );
    }
}

In the XAML I've got the DataGrid and DataForm defined as follows:

<data:DataGrid SelectionMode="Single"
               ItemsSource="{Binding Vehicles}"
               SelectedItem="{Binding SelectedVehicle, Mode=TwoWay}"
               AutoGenerateColumns="False"
               IsReadOnly="True">

<dataFormToolkit:DataForm CurrentItem="{Binding SelectedVehicle}" />

So as the SelectedItem changes on the DataGrid it should push that change back to the ViewModel and when the ViewModel raises the OnPropertyChanged the DataForm should refresh itself with the information for the newly-selected VehicleViewModel. However, the setter for SelectedVehicle is never being called and in the Output window of VS I'm seeing the following error:

System.Windows.Data Error: ConvertBack cannot convert value 'xxxx.ViewModel.VehicleViewModel' (type 'xxxx.ViewModel.VehicleViewModel'). BindingExpression: Path='SelectedVehicle' DataItem='xxxx.ViewModel.MainViewModel' (HashCode=31664161); target element is 'System.Windows.Controls.DataGrid' (Name=''); target property is 'SelectedItem' (type 'System.Object').. System.MethodAccessException: xxxx.ViewModel.MainViewModel.set_SelectedVehicle(xxxx.ViewModel.VehicleViewModel)

It sounds like it's having a problem converting from a VehicleViewModel to an object (or back again), but I'm confused as to why that would be (or even if I'm on the right track with that assumption). Each row/item in the DataGrid should be a VehicleViewModel (because the ItemsSource is bound to an ObservableCollection of that type), so when the SelectedItem changes it should be dealing with an instance of VehicleViewModel.

Any insight would be appreciated.

A: 

Your setter on the public VehicleViewModel SelectedVehicle is private so the DataGrid cannot modify it using the TwoWay mode. Your setter will need to be public.

DaveB
Well that's embarrassing. How's that for a case of not seeing the forest for the trees. I was so focused on what the exception was trying to tell me that I totally overlooked that. Removing the "private" from the setter fixed the problem. Thanks!
Craig W.