首页 > 解决方案 > 在 DataGrid WPF MVVM 中重新加载数据后如何保持对行的关注

问题描述

我到处搜索,找不到答案。使用绑定到 Web API http://localhost:3000/api/profiles的 WPF DataGrid ,以及如何在重新加载数据后保持对行的关注?

public class ProfilesViewModel : BaseViewModel
    {
private ObservableCollection<Profile> _Items;
        public ObservableCollection<Profile> Profiles { get => _Items; set { _Items = value; OnPropertyChanged(); } }

public PartyProfilesViewModel()
        {
DispatcherTimer dispatcherTimer = new DispatcherTimer();
            dispatcherTimer.Tick += dispatcherTimer_Tick;
            dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 1, 100);
            dispatcherTimer.Start();

}
private void dispatcherTimer_Tick(object sender, EventArgs e)
        {
            var client = new RestClient("http://localhost:3000");

            var reqData = new RestRequest("api/profiles", Method.GET);
            client.ExecuteAsync(reqData, resData =>
            {
                Profiles = JsonConvert.DeserializeObject<ObservableCollection<Profile>>(resData.Content);
            });

        }

}

谢谢!

标签: c#wpfmvvmdatagrid

解决方案


在 ViewModel 中添加所选项目的属性:

private _currentProfile=null;
public Profile CurrentProfile { get => _currentProfile; set { CurrentProfile = value; OnPropertyChanged(); } }

扩展您的 lambda(Equals()必须为Profile):

client.ExecuteAsync(reqData, resData =>
{
    var curProf = CurrentProfile;
    Profiles = JsonConvert.DeserializeObject<ObservableCollection<Profile>>(resData.Content);
    CurrentProfile=Profiles.FirstOrDefault((p)=>p.Equals(curProf));
});

并绑定CurrentProfileDataGrid.SelectedItemXAML 中:

<DataGrid ItemsSource="{Binding Profiles}" SelectionMode="Single" SelectedItem="{Binding CurrentProfile, Mode=TwoWay}">
</DataGrid>

推荐阅读