0
我是xamarin mvvm模式的初学者。目前我正在尝试创建一个搜索栏,从名称列表中搜索单词。我试图在我的视图模型上的Comman函数上编写一些代码,并将其绑定到搜索栏的SearchCommand
上。但它没有奏效。这里是我的代码使用mvvm模式的列表视图上的搜索栏的搜索命令
namespace HelloWorld.ViewModel
{
public class CustViewModel : INotifyPropertyChanged
{
private custmodel _custmodel;
public custmodel custmodel
{
get { return _custmodel; }
set
{
_custmodel = value;
NotifyPropertyChanged();
}
}
private string _message;
public string message
{
get { return _message; }
set
{
_message = value;
NotifyPropertyChanged();
}
}
private ObservableCollection<string> _list;
public ObservableCollection<string> Items
{
get
{
return _list;
}
set
{
_list = value;
NotifyPropertyChanged();
}
}
public Command SaveCommand
{
get
{
return new Command(() =>
{
message = "Your task : " + custmodel.name + ", " + custmodel.surname + " was successfully saved!";
});
}
}
private string _bar;
public string Bar
{
get { return _bar; }
set { _bar = value;
}
}
public Command SearchCommand
{
get
{
return new Command(() =>
{
string keyword = _bar;
IEnumerable<String> searchresult = _list.Where(name => name.Contains(keyword));
_list = new ObservableCollection<string>(searchresult);
NotifyPropertyChanged();
}
);
}
}
public CustViewModel()
{
custmodel = new custmodel
{
name = "Aasish",
surname = "Gurung",
email = "[email protected]"
};
_list = new ObservableCollection<string>();
_list.Add("Saurab");
_list.Add("Basanta");
_list.Add("Abhishek");
_list.Add("Surace");
_list.Add("Amir");
}
public event PropertyChangedEventHandler PropertyChanged;
//public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
这里是我的XAML文件
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="HelloWorld.Styling"
BackgroundColor="AntiqueWhite" Title="Hello"
xmlns:converters="clr-namespace:HelloWorld.Converters; assembly=HelloWorld">
<StackLayout>
<SearchBar x:Name="MainSearchBar" Text="{Binding Bar}"
SearchCommand="{Binding SearchCommand}"/>
<ListView ItemsSource="{Binding Items}"/>
</StackLayout>
谢谢你,感谢你的帮助。如果搜索栏上的文本为空,我希望返回带有完整列表的列表视图。我该怎么做? –
@AasishGrg最好问一个新问题,而不是在同一篇文章中询问多个问题,但是您必须保留一个包含所有项目的单独列表,或者对数据API进行新的调用(如果有的话) ,并要求提供完整的清单。 – hvaughan3