首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >MVVM搜索栏Xamarin.Forms

MVVM搜索栏Xamarin.Forms
EN

Stack Overflow用户
提问于 2018-09-15 10:13:34
回答 2查看 6.5K关注 0票数 1

我试图在Xamarin.forms中使用MVVM实现一个搜索栏。到目前为止,我已经设法从互联网上借用了一些代码,而且它似乎确实经过了搜索的过程。唯一的问题是我不知道在命令中放什么代码。

我希望搜索栏可以从一个列表中搜索recipeNames。这些信息都存储在本地数据库中,并使用可观察的集合显示。

你能帮我解决这个问题吗?

XAML

代码语言:javascript
复制
<SearchBar x:Name="SearchBar" 
               Placeholder="Search" 
               SearchCommand="{Binding SearchCommand}" 
               SearchCommandParameter="{Binding Text, Source={x:Reference SearchBar}}"
               Text="{Binding SearchText, Mode=TwoWay}">
        <SearchBar.Behaviors>
            <local:TextChangedBehavior />
        </SearchBar.Behaviors>
    </SearchBar>
    <ListView x:Name="ListViewItems"
          ItemsSource="{Binding Recipes}"
          IsPullToRefreshEnabled="True"
          Refreshing="ListViewItems_Refreshing"
          SelectedItem="{Binding SelectedRecipe}">

文本更改行为

代码语言:javascript
复制
    class TextChangedBehavior: Behavior<Xamarin.Forms.SearchBar>
{
    protected override void OnAttachedTo(Xamarin.Forms.SearchBar bindable)
        {
            base.OnAttachedTo(bindable);
            bindable.TextChanged += Bindable_TextChanged;
        }

        protected override void OnDetachingFrom(Xamarin.Forms.SearchBar bindable)
        {
            base.OnDetachingFrom(bindable);
            bindable.TextChanged -= Bindable_TextChanged;
        }

        private void Bindable_TextChanged(object sender, TextChangedEventArgs e)
        {
            ((Xamarin.Forms.SearchBar)sender).SearchCommand?.Execute(e.NewTextValue);
        }

    }

和viewModel

代码语言:javascript
复制
public class RecipeListViewModel : ObservableCollection<Recipe>
{
    private ObservableCollection<Recipe> Recipes {get; set;}
    public INavigation Navigation { get; internal set; }
    public ICommand NewAddPage { get; protected set; }
    public RecipeListViewModel(INavigation navigation)
    {
        this.Navigation = navigation;
        Recipes = new ObservableCollection<Recipe>();
        this.NewAddPage = new Command(async () => await CreateNewAddPage());
        Init();
    }

    // Gets all recipes from the database and adds them to the observable collection
    private void Init()
    {
        var enumarator = App.RecipeDbcontroller.GetRecipe();
        if (enumarator == null)
        {
            App.RecipeDbcontroller.SaveRecipe(new Recipe { RecipeName = "Moussaka", Serves = 6, PrepTime = "30", CookTime = "2 Hours", MealType = "Dinner" });

            enumarator = App.RecipeDbcontroller.GetRecipe();
        }
        while (enumarator.MoveNext())
        {
            //cleans database of all empty records
            if (enumarator.Current.RecipeName == null || enumarator.Current.CookTime == null)
            {
                App.RecipeDbcontroller.DeleteRecipe(enumarator.Current.RecipeID);
            }
            else
                Add(enumarator.Current);
        }
    }


    private ICommand _searchCommand;
    public ICommand SearchCommand
    {
        get
        {
            return _searchCommand ?? (_searchCommand = new Command<string>((text) =>
            {
                **// THIS IS WHAT I DON'T KNOW WHAT TO DO**
            }));
        }
    }

    private string _searchText { get; set; }
    public string SearchText
    {
        get { return _searchText; }
        set
        {
            if (_searchText != value)
            {
                _searchText = value;
            }
            OnPropertyChanged();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

RecipeDatabaseController类

代码语言:javascript
复制
 public RecipeDatabaseController()
        {
            this.database = DependencyService.Get<ISQLite>().GetConnection();
            this.database.CreateTable<Recipe>();
        }

        //Recipe CRUD
        public IEnumerator<Recipe> GetRecipe()
        {
            lock (locker)
            {
                if (database.Table<Recipe>().Count() == 0)
                {
                    return null;
                }
                else
                {
                    return this.database.Table<Recipe>().GetEnumerator();
                }
            }
        }

        public IEnumerator<Recipe> GetRecipeBySearchTerm(text)
        {
            var enumarator = GetRecipe();
            lock (locker)
            {
                while (enumarator.MoveNext)
                {
                    if(enumarator.Current.RecipeName.Contains(text)
                        return this.
                }
            }
        }

        public int SaveRecipe(Recipe recipe)
        {
            lock (locker)
            {
                if (recipe.RecipeID != 0)
                {
                    this.database.Update(recipe);
                    return recipe.RecipeID;
                }
                else
                {
                    return this.database.Insert(recipe);
                }
            }
        }

        public int DeleteRecipe(int Id)
        {
            lock (locker)
            {
                return this.database.Delete<Recipe>(Id);
            }
        }
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-09-18 07:25:29

对,搜索命令应该是这样的。

代码语言:javascript
复制
public ICommand SearchCommand => _searchCommand ?? (_searchCommand = new Command<string>((text) =>
{
    if (text.Length >=1)
    {
        Recipes.Clear();
        Init();
        var suggestions = Recipes.Where(c => c.RecipeName.ToLower().StartsWith(text.ToLower())).ToList();
        Recipes.Clear();
        foreach (var recipe in suggestions)
         Recipes.Add(recipe);

    }
    else
    {
        Recipes.Clear();
        Init();
        ListViewVisible = true;
        SuggestionsListViewVisible = false;
    }

}));
票数 2
EN

Stack Overflow用户

发布于 2018-09-15 11:25:59

代码语言:javascript
复制
using System.Linq;

    //Recipe CRUD
    public IEnumerable<Recipe> GetRecipe()
    {
        lock (locker)
        {
            return this.database.Table<Recipe>();
        }
    }

    public IEnumerable<Recipe> GetRecipeBySearchTerm(string text)
    {
        var recipes = GetRecipe();
        lock (locker)
        {
            return recipes.Where(m => m.RecipeName.ToLower().Contains(text));
        }
    }

添加using System.Linq引用

更改这两个方法并返回IEnumerable

请注意。RecipeName是您要使用的筛选菜谱的属性。

和您的搜索命令如下

代码语言:javascript
复制
private ICommand _searchCommand;
public ICommand SearchCommand
{
    get
    {
        return _searchCommand ?? (_searchCommand = new Command<string>((text) =>
        {
            var filteredRecipes = App.RecipeDbcontroller.GetRecipeBySearchTerm(text);

            recipes.Clear();
            foreach(var recipe in filteredRecipes )
                 recipes.Add(recipe);
        }));
    }
}

我还没有测试过这段代码,所以不确定在哪里可能会出现错误,但是您可以计算出其余的代码,因为逻辑是交给您的。

祝好运

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52343744

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档