我正在使用以下代码,我正在遵循 MVVM 设计模式
在 Veiw Page 中编写以下代码:-
internal class NotificationsPage : ContentPage
{
#region Variables and Controlls declaration
private NotificationsViewModel _viewModel;
private SearchBar _notificationSearchBar;
#endregion Variables and Controlls declaration
#region Constructor
public NotificationsPage()
{
BindingContext = App.Locator.Notification;
_viewModel = BindingContext as NotificationsViewModel;
_notificationSearchBar = new SearchBar()
{
};
_notificationSearchBar.SetBinding(SearchBar.TextProperty,"TEXT");
_notificationSearchBar.SetBinding(SearchBar.SearchCommandProperty,"SearchCommand" );
}
在viewModel中可以
#region Search Functionality
#region Commands
private RelayCommand _searchCommand;
public RelayCommand SearchCommand
{ get { return _searchCommand ?? (_searchCommand = new RelayCommand(async () =>
{
if (SearchedList.Count > 0)
{
if (!string.IsNullOrEmpty(Text))
{
List<Notification> entities = SearchedList.Where(e =>
Convert.ToString(e.NotificationSubject).ToLower().Trim().Contains(Text.ToLower().Trim())
|| Convert.ToString(e.LinkedRecordName).ToLower().Trim().Contains(Text.ToLower().Trim())
|| Convert.ToString(e.NotificationDateSent).ToLower().Trim().Contains(Text.ToLower().Trim())
|| Convert.ToString(e.NotificationContent).ToLower().Trim().Contains(Text.ToLower().Trim())).ToList();
NotificationsList = new ObservableCollection<Notification>(entities);
}
else
{
NotificationsList = SearchedList;
}
}
}
)); } }
private string _searchText = string.Empty;
public string Text // This is the text property we bind on page _notificationSearchBar.SetBinding(SearchBar.TextProperty,"TEXT");
{
get { return _searchText; }
set
{
if (_searchText != value)
{
_searchText = value;
Set(() => Text, ref _searchText, value);
if (SearchCommand.CanExecute(null))
{
SearchCommand.Execute(null);
}
}
}
}
#endregion
#endregion
其中 SearchedList 和 NotificationList 是绑定到列表的可观察集合,您也可以将其作为类列表
private ObservableCollection<Notification> _notificationsList;
public ObservableCollection<Notification> NotificationsList
{
get { return _notificationsList; }
set
{
Set(() => NotificationsList, ref _notificationsList, value);
}
}
/// <summary>
/// Holds Searched notifications
/// </summary>
private ObservableCollection<Notification> _searchedList;
public ObservableCollection<Notification> SearchedList
{
get { return _searchedList; }
set
{
Set(() => SearchedList, ref _searchedList, value);
}
}