【发布时间】:2019-08-09 04:35:35
【问题描述】:
我正在开发 Xamarin.Forms 应用程序。它在 NavigationBar 中有 SearchBar,在 ContentPage 中有 ListView,在底部有一个带有 AddButton 的条目。当用户单击AddButton 时,条目中的文本将添加到领域移动数据库中。其中自动刷新IEnumerable。 bind 到 IEnumerable auto updates 的 ListView。
public class MainViewModel : ReactiveObject
{
public IEnumerable<Company> Companies { get; set; }
[Reactive]
public string Query { get; set; }
public string NewCompany { get; set; }
public ReactiveCommand<Unit, Unit> AddCompanyCommand { get; set; }
public ReactiveCommand<Unit, IEnumerable<Company>> SearchCommand { get; set; }
Realm _realm;
public MainViewModel()
{
_realm = Realm.GetInstance();
Companies = _realm.All<Company>();
AddCompanyCommand = ReactiveCommand.CreateFromTask(async () => await AddButtonClicked());
SearchCommand = ReactiveCommand.Create<Unit, IEnumerable<Company>>(
_ =>
SortCollection()
);
SearchCommand.ToProperty(this, nameof(Companies));
this.WhenAnyValue(x => x.Query).Throttle(TimeSpan.FromSeconds(1)).Select(_ => Unit.Default).InvokeCommand(this, x => x.SearchCommand);
}
async Task AddButtonClicked()
{
if (!string.IsNullOrWhiteSpace(NewCompany))
{
_realm.Write(() =>
{
_realm.Add(new Company { Name = NewCompany });
});
NewCompany = string.Empty;
}
}
IEnumerable<Company> SortCollection()
{
if (string.IsNullOrWhiteSpace(Query))
{
Companies = Companies.Where(x => x.Name != string.Empty);
}
else
{
Companies = Companies.Where(x => x.Name.IndexOf(Query, StringComparison.InvariantCultureIgnoreCase) >= 0);
}
return Companies;
}
}
最近,当我将搜索逻辑添加到 ViewModel 时,ListView 不会自动更新。我要么必须 search 要么重新启动应用程序以在 ListView 中显示 new item。当我注释掉以下行时,ListView 开始自动更新。
SearchCommand.ToProperty(this, nameof(Companies));
但随后它停止显示搜索结果。我希望使用新项目自动更新并在 ListView 中显示搜索结果功能。
【问题讨论】:
标签: xamarin.forms realm reactiveui