Wednesday, 28 January 2015

Xamarin Forms contacts search

I’m in the middle of writing a Xamarin Forms app and today I needed to add in a contacts search page, and remembered that James Montemagno had created a plugin that exposes contacts in a platform neutral manner so I downloaded it and used it in my app.

I also wanted to add a search bar, and again there’s a control in XF for that, so I ended up with (somewhat simplified) the following XAML…

  
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<SearchBar x:Name="search" Placeholder="Search">
</SearchBar>
<ListView Grid.Row="1" ItemsSource="{Binding FilteredContacts}"
IsGroupingEnabled="true" GroupDisplayBinding="{Binding Key}"
GroupShortNameBinding="{Binding Key}">
<ListView.ItemTemplate>
<DataTemplate>
<TextCell Text="{Binding Name}" TextColor="Black"
Detail="{Binding PhoneNumber}" DetailColor="Gray">
</TextCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>

I have removed some of the XAML as it’s not that important to this post (it’s available in the download). Now, with that in place (and a load of code in the view model which I’ll get to in a minute) I got a UI as follows…


iOS Simulator Screen Shot 28 Jan 2015 22.32.19


So far so good. Then I needed to hook up the search box, and as I’m using XAML (and if you’re not, you should give it a try as it’s way easier to create UI’s using it) I needed a way to bind to the search box to that I could respond to the TextChanged event.


Another excellent package that you’ll want to use it the Xamarin.Behaviors package by Corrado – massive thanks to him for putting this together, it’s excellent!


Behaviors to the rescue


By adding a behavior into the XAML, I can handle an event – so in this case I added the following to the SearchBar…

  <SearchBar x:Name="search" Placeholder="Search">
<b:Interaction.Behaviors>
<b:BehaviorCollection>
<b:EventToCommand EventName="TextChanged"
Command="{Binding SearchTextChanged}"
CommandParameter="{Binding Text, Source={x:Reference search}}"/>
</b:BehaviorCollection>
</b:Interaction.Behaviors>
</SearchBar>

This hooks the TextChanged event of the search bar, calls the SearchTextChangedCommand on my view model, and passes through the value of the Text property of the search bar. Yay!.


Or not.


The problem I found was that my command was being passed a string, but it was the text before the ne character was entered, so say I pressed ‘X’ in an empty search bar, my code would be called with an empty string. Pressing ‘A’ next, my command would get ‘X’, and pressing ‘M” next, my code would get ‘XA’. I was always getting the data just prior to the new character – so I guess that the TextChanged event should be more clearly termed as the TextChanging event.


Anyway, I needed to fix this – so looked at the actual event and it contains two properties, the current text and the new value. All I needed to do was get the new vale of the event arguments and I’d be away.


To the best of my knowledge there is no way to bind to the event arguments, you need to write some additional code (this was true in WPF and Silverlight, I’ve done exactly the same there too). So, I cranked out a new behavior that attaches to the SearchBar’s TextChanged event, and calls the command with the new value of the text property. My XAML is therefore this…

  <SearchBar x:Name="search" Placeholder="Search">
<b:Interaction.Behaviors>
<b:BehaviorCollection>
<bh:SearchBarTextChanged Command="{Binding SearchTextChanged}"/>
</b:BehaviorCollection>
</b:Interaction.Behaviors>
</SearchBar>

Here I'm using my SearchBarTextChanged behavior to hook to the SearchTextChanged command, and sure enough now when I type in the search bar I get the desired effect. Excellent!


Filtering in code


In the view model I use James’ contacts plugin to select all contacts that have a mobile phone, and that have at least a forename or surname (my real code blew up on a colleagues iPhone as he has a contact with just a company name). I tuck this list away as the source, and then create a filtered collection from the source and the filter statement.

CrossContacts.Current.PreferContactAggregation = false;
var hasPermission = CrossContacts.Current.RequestPermission().Result;

if (hasPermission)
{
// First off convert all contacts into ContactViewModels...
var vms = CrossContacts.Current.Contacts.Where(c => Matches(c))
.Select(c => new ContactViewModel(c));

// And then setup the contact list
var grouped = from contact in vms
orderby contact.Surname
group contact by contact.SortByCharacter into contactGroup
select new Grouping (contactGroup.Key, contactGroup);

foreach (var g in grouped)
{
_contacts.Add (g);
_filteredContacts.Add (g);
}
}

The above code uses some Linq to select all contacts and group them by first character of their surname. I created a simple Matches(contact) function that checks that the contact has a mobile phone number and also that they have one of forename or surname.


Then I have the code that is called to filter the collection when you type text into the search bar...

private void FilterContacts(string filter)
{
_filteredContacts.Clear ();

if (string.IsNullOrEmpty(filter))
{
foreach (var g in this.Contacts)
_filteredContacts.Add (g);
}
else
{
// Need to do some filtering
foreach (var g in this.Contacts)
{
var matches = g.Where (vm => vm.Name.Contains (filter));

if (matches.Any())
{
_filteredContacts.Add (new Grouping (g.Key, matches));
}
}
}
}

This is a bit ropey but does the trick. As the collection is an ObservableCollection, any changes are shown in the UI immediately.


Code


I’ve created a simple example project (the one shown above) that you can download. Hopefully this will help someone out. I’ve not tried this on Android or Windows Phone as yet, but as none of the code is in the platform specific library I can’t see any reason for it not to work on those platforms too.


Bye for now!

37 comments:

Mr. Nam said...
This comment has been removed by a blog administrator.
James Martin said...

From this post, developer can easily learn the logics of Xamarin Forms. Coding which he share in this post is also useful to learn the process. Creative Android Event App

Michael Miceli said...

Thank you. I also ran into the issue of the oldVal and newVal on the behavior command. Your blog got me where I needed to go with the custom behavior.

Oliver Maurice said...

Check out the best app to record phone calls from this blog article

alex mark said...

PCs embrace the presence of palm-sized machines, enclose chips get changed to microchips and organizations discharge updates to improve their product. Search Bar Firefox 57 Quantum addon

Lou Pacheco said...

Your posts have more meaning for me.
writemyessay thanks for sharing.

Ruth Sloan said...

Such a great blog is very difficult to get. I am very happy to join this Blog in today gangstar vegas modded apk download zombie tsunami mod apk android cooking fever mod game

Nathan William said...

Every single student is searching for a proper essay generator who can understand the need of the work and do the essay completely flawless. However, it often happens that students fail to figure out who can be one of the best instant essay typer for their work.
Academic essay writing has been a parameter to judge the merits of the students for a long time. The present time is none the less. In fact, as time is passing by, students are having more and more requirements to write an essay that will be graded. Hence seeking Do my essay help is on the rise and it will be.

MyAssignmentHelpAu said...

This post is not just informative but impressive also. The post is so convincing that it created an urge to choose My Assignment Help Australia services. You can email us at cs@Myassignmenthelpau.Com or Phone Number: +61-2-8005-8227

Serafim Rostiw said...

We are a reputable writing company mental health argumentative essay topics of international experience with creation of different types of essays for students of all levels of education. We have a team of professional writers of all possible scientific areas. That is why our agency is always confident about our essays being of the top quality. The assignments we provide for our customers always contain relevant information and facts.

Due to a number of factors, the mental medicine is nowadays one of extremely popular scientific directions as long as scientists from all over the world explore the reasons for psychological problems, mental health argumentative essay, and the ways to overcome and treat them. People’s psychological peculiarities, behavior, and reactions to various factors and circumstances are under discussion and are carefully examined.

Nikki Heysen said...
This comment has been removed by the author.
Nikki Heysen said...

Students struggle too much in finishing their academic task, that is why the team of professional writers at StudentsAssignmentHelp.com is here to give you its Assignment Writing Services. Our online assignment makers understand all your requirements and work in the asked direction to prepare an accurate assignment.

Unknown said...

Very nice blog and articles. I am really very happy to visit your blog. Now I am found which I actually want. I check your blog everyday and try to learn something from your blog. Thank you and waiting for your new post. Assignment help Australia

demon smith said...

Very good article.Your language is very simple anybody can read your article.You have good knowledge of writing.I think you got online assignment help in Uae.Students assignment help gives very good assignment writing help online.

Ireland Assignment Help said...

recently found many useful information in your website especially this blog page. Among the lots of comments on your articles. Thanks for sharing. homework help

Stefan Carl said...

Find the best way of getting an Online Assignment Help on studentsassignmenthelp.com. Students assignment help have very genuine assignment writing services given by experts in the UAE.

uae assignment help said...

uaeassignmenthelp.com is a one of best service . uae assignment support is help to complete assignment in required time. if you faced any problem different subject maths, science, finance , dissertation etc. you can email us on info@uaeassignmenthelp.com

Make My Assignment said...

If you studying in college and looking for college assignment help then your search ends here. Get assignment help from one of the leading assignment writing company working across the globe.

Assignment Help said...

Thanks for providing such beautiful information. Can anyone Write my Assignment For me?, Worry no more and ask the experts of complete my assignment for assistance. Our experts will finish your task in the proper format and structure the paper well according to your university guidelines.

andrea Rose said...

I read your blog post and this is nice blog post.. thanks for taking the time to share with us. have a nice day daily forex robot ea review

Nathan William said...

Statistics is one of the most difficult subjects that are taught in the colleges and universities, and if you don’t particularly enjoy collection and analysis of data, you may have a difficult time coping with the academic pressure. Like any other field of academics, you also need to draft a number of statistics assignment help throughout the semester, and since they carry a significant amount of marks, there’s no way to avoid these daunting tasks
One of the most prominent issues the students have to deal with while writing assignments is plagiarism. Hence, they extensively use plagiarism checker to check if there are any copied content in the paper.
Another major reason for using plagiarism checkers is that universities do not accept plagiarized content. Plagiarism is a serious offence. Hence, if found, the students are suspended or might even lose the grades.

Emma Watson said...

We the Best Assignment Experts are always ready to help those students who are facing problem for their assignments. We are offering University Assignment Help, Assignment Help London, Cheap Assignment Help, Help with Assignment like these types of help through online and our work cost is very minimal.


https://www.bestassignmentexperts.com/best-assignment-help

Sophie Grace said...

net worth
michael blakey net worth

jeff kaplan net worth

jeff kaplan net worth

chris d"elia net worth

james rolfe net worth

kirk cameron net worth

chris d"elia net worth

sean evans net worth

erin brockovich net worth

Students Assignment Help said...

Students Assignment Help serves the best coursework writing help UK services to the college or university students at a reasonable price. To score good marks in their college, they can avail our excellent services. Our writer can write challenging homework assignments as they are well-versed with every academic topic.

dịch thuật miền trung said...

Thank for Baì viết hữu ích. Mình cũng muốn giới thiệu về một Công ty dịch thuật uy tín - Công ty CP dịch thuật miền trung - MIDtrans địa chỉ 02 Hoàng Diệu, TP Đồng Hới, tỉnh Quảng Bình có Giấy phép kinh doanh số 3101023866 cấp ngày 9/12/2016 là đơn vị chuyên cung cấp dịch vụ dịch thuật, phiên dịch dành các cá nhân. Hệ thống thương hiệu và các Công ty dịch thuật con trực thuộc: công ty dịch thuật sài gòn 247 địa chỉ 47 Điện Biên Phủ, Phường Đakao, Quận 1 TP HCM, dịch thuật bình dương : địa chỉ 123 , Lê trọng tấn, dĩ an, bình dương là nhà cung ứng dịch vụ dịch thuật uy tín hàng đầu tại bình dương viet translate : dịch vụ dịch thuật cho người nước ngoài có nhu cầu, giao diện tiếng Anh dễ sử dụng; dịch thuật công chứng quận 9 (chín) : nhà cung ứng dịch vụ dịch vụ dịch thuật phiên dịch hàng đầu tại Quận 9 (chín), TP HCM; công ty dịch thuật Đà Nẵng : Địa chỉ 54 Đinh Tiên Hoàng, Quận Hải Châu, TP Đà Nẵng chuyên cung cấp dịch vụ dịch thuật công chứng, dịch thuật chuyên ngành tại Đà Nẵng. Chúng tôi chuyên cung cấp các dịch vụ biên dịch và phiên dịch, dịch thuật công chứng chất lượng cao hơn 50 ngôn ngữ khác nhau như tiếng Anh, Nhật, Hàn, Trung, Pháp, Đức, Nga, Tây Ban Nha, Bồ Đào Nha, Ý, Ba Lan, Phần Lan, Thái Lan, Hà Lan, Rumani, Lào, Campuchia, Philippin, Indonesia, La Tinh, Thụy Điển, Malaysia, Thổ Nhĩ Kỳ..vv... Dịch thuật MIDtrans tự hào với đội ngũ lãnh đạo với niềm đam mê, khát khao vươn tầm cao trong lĩnh vực dịch thuật, đội ngũ nhân sự cống hiến và luôn sẵn sàng cháy hết mình. Chúng tôi phục vụ từ sự tậm tâm và cố gắng từ trái tim những người dịch giả.Tự hào là công ty cung cấp dịch thuật chuyên ngành hàng đầu với các đối tác lớn tại Việt nam trong các chuyên ngành hẹp như: y dược (bao gồm bệnh lý), xây dựng (kiến trúc), hóa chất, thủy nhiệt điện, ngân hàng, tài chính, kế toán. Các dự án đã triển khai của Công ty dịch thuật chuyên nghiệp MIDtrans đều được Khách hàng đánh giá cao và đạt được sự tín nhiệm về chất lượng biên phiên dịch đặc biệt đối với dịch hồ sơ thầu , dịch thuật tài liệu tài chính ngân hàng, dịch thuật tài liệu y khoa đa ngữ chuyên sâu. Đó là kết quả của một hệ thống quản lý chất lượng dịch thuật chuyên nghiệp, những tâm huyết và kinh nghiệm biên phiên dịch nhiều năm của đội ngũ dịch giả của chúng tôi. Hotline: 0947688883. email: info@dichthuatmientrung.com.vn . Các bạn ghé thăm site ủng hộ nhé. Cám ơn nhiều

Assignment Help said...

Your blog provided with valuable information. Most of the times, students get stressed due to their assignments.thanks for this blog it's really helpful for students.
Data Structure Assignment Help

website designer said...

Your blog provided with valuable information. Most of the times, students get stressed due to their assignments.thanks for this blog it's really helpful for students.
Website Design Company

Liam said...

The second positive aspect of Online Assignment Help is that they are available 24*7 to you. No matter what the time is or what the situation is they are ready to help you anytime. So the student can take their help anytime.Programming Help

Theresa Delcas said...

My Assignment Services is an effective provider of Australia Assignment Help and online tutoring services from last decade. They are constantly increasing their horizon by expanding their services to suit the demands of students across the world. They have more than 2000 experts who are constantly on top of their expertise to bring them a much experienced Property law assignment help to students. This is the reason students rely so much on our finance assignment help experts world-wide. So, send in all your queries to us and see them being solved by us in no time. My Assignment Services has been the leading Assignment Help USA organisation globally. With providing assistance with a wide range of topics, we also specialise in providing helpful samples and reference assignment solutions too. So, contact us for any help, in any subject. Moreover, our writers ensure that each assessment task is drafted exactly according to the marking rubric and adheres the guidelines as provided by your lecturer. My Assignment Services is an erudite firm that works with an aim of providing utmost satisfaction to their clients. The assignment assistance is available for all 24 hours and you can chat with our expert any time of the day or night. With 100% plagiarism-free solutions, time-delivery, and in-depth check up of grammatical errors, students can easily score well with our Humanities Assignment Help Australia.

kristen said...

Students Assignment Help ethical place where students can get help in writing research paper outstandingly at the low price. Our professional academic essay writers always strive to help students in accomplishing their assignment work.

Kerrthika K said...

Nice post and more informative,thanks for sharing.
informatica mdm training
Informatica MDM Training in Chennai
Informatica Training Institute in Chennai
ionic course in chennai
IoT courses in Chennai
Data Analytics Courses in Chennai
Blockchain Training in Chennai

latest news said...

Thanks for sharing us valuable content.... Want to get more Business news and latest news in simple language must visit

AB Assignment Help said...

Your article is very informative for me. Contact us if you want to online assignment help. AbAssignmentHelp delivers unique and quality content that will be completely related to your assignment.

Puremelda said...

Our Pay for custom dissertation writing, customer access our custom dissertation writing services knowing that they are assured of the best online essay writing services by our research paper companies.

meldaresearch said...

As you order for nursing research paper writing service you must find out if your essay writing company offers extra facilities like making corrections and amendments if there are mistakes made by writers. You can also write my research paper online.

Robert Smith said...

Very helpful advice in this particular post! It’s the little changes that make the largest changes. Essay Help

Puremelda said...

We deliver our affordable research papers ahead of deadlines and time frame you specify more often than not, having an insight on the significance of timely submission of the best assignment writing service to institution departments.