c# - 在 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);
});
}
}
谢谢!
解决方案
在 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));
});
并绑定CurrentProfile
到DataGrid.SelectedItem
XAML 中:
<DataGrid ItemsSource="{Binding Profiles}" SelectionMode="Single" SelectedItem="{Binding CurrentProfile, Mode=TwoWay}">
</DataGrid>
推荐阅读
- python - 通过函数添加减法值并将数据附加到 for 循环的列表中
- python - \b 等效于在 python 中保持零宽度的 unicode 正则表达式
- c++ - 致命错误:dcmtk/config/osconfig.h:没有这样的文件或目录
- wordpress - 向每 100 个页面访问者显示不同的内容(wordpress)
- python - 将年份数字转换为 'yyyy-mm-dd' 格式
- reactjs - 错误 #11322 - 您网站的“gatsby-node.js”创建了一个页面,但没有将路径传递给组件
- python - `ast.literal_eval` 的最快实现
- c# - 尝试使用 memorystream 显示 PDF 时无法评估表达式错误
- recursion - 尝试将递归用于斐波那契数列(JAVA)时出现越界异常
- r - 如何将值的数量转换为其在 R 中的区间?