属性更改时如何从集合中保存项目?

时间:2017-02-11 09:07:34

标签: c# .net wpf mvvm mvvm-light

我有一个显示体育列表的DataGrid,我希望在IsActive属性更改时保存运动。我怎么能用MVVM风格呢?我正在使用MVVM Light框架。

这是我的DataGrid

         <DataGrid ItemsSource="{Binding SportsList}" AutoGenerateColumns="False" CanUserAddRows="False">
            <DataGrid.Columns>
                <DataGridTextColumn Foreground="Black" Width="200" Header="Name" Binding="{Binding Name, Mode=TwoWay}" IsReadOnly="True" />
                <DataGridCheckBoxColumn Width="60" Header="Is Active" Binding="{Binding IsActive, Mode=TwoWay}" IsReadOnly="False" />
            </DataGrid.Columns>
        </DataGrid>

视图模型的外观如下:

public class MainViewModel : ViewModelBase
{
    private readonly ISportService _sportService;

    private ObservableCollection<SportModel> sports;

    public MainViewModel(ISportService sportService)
    {
        _sportService = sportService;
        sports = new ObservableCollection<SportModel>();
        LoadSportsCommand = new RelayCommand(LoadSports);
        SaveSportCommand = new RelayCommand(SaveSport);
    }

    public ICommand LoadSportsCommand { get; private set; }
    public ICommand SaveSportCommand { get; private set; }

    public ObservableCollection<SportModel> SportsList
    {
        get
        {
            return sports;
        }
    }

    private void SaveSport()
    {
            // Todo
    }

    private void LoadSports()
    {
        sports.Clear();
        foreach (var sport in _sportService.GetAllSports())
        {
            sports.Add(new SportModel()
            {
                Name = sport.Name,
                IsActive = sport.IsActive
            });
        }
    }
}

这是SportModel:

public class SportModel : ObservableObject
{    
    public string Name { get; set; }

    public bool IsActive { get; set; }
}

1 个答案:

答案 0 :(得分:1)

一些修改可以解决问题:

private void LoadSports()
{
    // ... your code
    foreach (var r in SportsList)
        r.PropertyChanged += A_PropertyChanged;
}

private void A_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
     SaveSport((SportModel)sender);
}

private void SaveSport(SportModel sport)
{
     // Todo
}

public class SportModel : ObservableObject
{
    public string Name { get; set; }

    bool _isactive;
    public bool IsActive
    {
        get { return _isactive; }
        set
        {
            if (_isactive != value)
            {
                _isactive = value;
                RaisePropertyChanged("IsActive");
            }
    }
}
protected override void RaisePropertyChanged([CallerMemberName] string propertyName = null)
 {
     base.RaisePropertyChanged(propertyName);
 }
}

最好在Xaml中使用 UpdateSourceTrigger = PropertyChanged

 <DataGridCheckBoxColumn Width="60" Header="Is Active" Binding="{Binding IsActive, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" IsReadOnly="False" />