Synchronize DataGrid and DataForm in Silverlight 3

Posted by SpiralGray on Stack Overflow See other posts from Stack Overflow or by SpiralGray
Published on 2010-04-11T16:23:58Z Indexed on 2010/04/12 4:53 UTC
Read the original article Hit count: 451

Filed under:
|
|

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.

© Stack Overflow or respective owner

Related posts about Silverlight

Related posts about datagrid