开发者

Synchronize DataGrid and DataForm in Silverlight 3

开发者 https://www.devze.com 2022-12-26 16:55 出处:网络
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 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 SelectedIt开发者_StackOverflow社区em changes it should be dealing with an instance of VehicleViewModel.

Any insight would be appreciated.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号