2015-07-03 44 views
0

我正在使用mvvm Light,我想要的是在我的數據網格中添加/刪除一些行。顯示初始值,但是當我添加一些信息時,我的集合中填入了我輸入的值,但其類型爲GalaSoft.MvvmLight.ObservableObject而不是「MyType」,因此當我想要刪除新添加的行時,我的應用程序會分裂(SelectedItem是空)...(如果我想刪除一個沒有手動添加的行,它就起作用了!)。在datagrid中添加行不能按預期方式工作mvvm light

<DataGrid Name="Table" ItemsSource="{Binding MyCollection}" SelectedItem="{Binding SelectedItem}" IsSynchronizedWithCurrentItem="True"> 
      <DataGrid.Columns> 
       <DataGridTextColumn Header="ID" Width="*" Binding="{Binding Path=Id,Mode=TwoWay}" /> 
       <DataGridTextColumn Header="Name" Width="*" Binding="{Binding Path=Name,Mode=TwoWay}" /> 
    </DataGrid.Columns> 

在視圖模型

public MyType SelectedItem 
{ 
    get { return _selectedItem; } 
    set 
    { 
    _selectedItem = value; 
    RaisePropertyChanged(); 
    } 
} 
public ObservableCollection<ObservableObject> MyCollection 
{ 
    get 
    { 
    return _myCollection; 
    } 
    set 
    { 
    _myCollection = value; 
    RaisePropertyChanged(); 
    } 
} 
public RelayCommand RemoveRow { get { return new RelayCommand(RemoveRowCommand, CanRemove); } } 
public RelayCommand AddRow { get { return new RelayCommand(AddRowCommand, CanAdd); } } 

public void RemoveRowCommand() 
{ 
    MyCollection.Remove(SelectedItem); 
} 

public void AddRowCommand() 
{ 
    MyCollection.Add(SelectedItem); 
} 

回答

0

讓你的類繼承BindableBase。 作出財產LIK這

private ObservableColletion<ObservableObject> _myCollection; 
public ObservableCollection<ObservableObject> MyCollection 
{ 
    get 
    { 
    return _myCollection; 
    } 
    set 
    { 
    SetProperty(ref _myCollection,new ObservableCollection<ObservableObject>(value)); 
    } 
} 

SetProperty方法(從BindableBase類)需要大約提高屬性更改事件的照顧。它應該工作:)