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…
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!
257 comments:
«Oldest ‹Older 201 – 257 of 257In T20s, momentum is everything—those explosive batters mentioned here could flip games in just a few overs. SRH vs GT Dream11 Prediction IPL 2025 Spot-on predictions!
T20 is all about impact players, and this analysis nails the ones to watch. 3 Reasons Punjab Kings Lost To Rajasthan Royals Don’t be surprised if they light up the tournament.
In today’s fast paced online world, businesses need professionals with cutting edge skills. Enrolling in a Digital Marketing course in Coimbatorehelps you stay ahead of the competitor by mastering SEO, PPC and cultural media strategies.
If those finishers click at the right time, they’ll steal games out of nowhere. GT vs RR Dream11 Prediction IPL Love the sharp focus in these picks.
These predictions feel on point. PBKS vs CSK Dream11 Prediction IPL The combo of big hitters and clever bowlers here screams match-winners.
I’m backing these players too—T20 rewards risk-takers, and this list is full of them. KKR vs LSG Match Prediction Can’t wait for the thrillers ahead!
These aren’t just predictions—they’re warnings to the other teams. GT vs RR Dream11 Prediction IPL If these guys fire, it’s game over!
You’ve nailed the potential game-breakers—T20s are short, sharp, and unpredictable, KKR vs LSG Match Prediction but these players bring consistency.
Great read! RCB vs DC Dream11 Prediction IPL 2025 If these bowlers hit their rhythm, they could shut down even the biggest hitters in the format.
Love the mix of firepower and finesse in these predictions. GT vs RR Dream11 Prediction IPL 2025 T20 is all about striking that balance.
These predictions scream T20 brilliance—expect game-turning cameos CSK vs KKR Dream11 Prediction IPL and last-over thrillers from these stars!
Love how this highlights impact players—exactly what makes or breaks T20 contests. RCB vs DC Match Prediction Big moments incoming!
Pinpoint predictions! T20s reward instinct and boldness, KKR vs LSG Match Prediction and these names fit the bill perfectly.
Solid prediction lineup! MI vs RCB Match Prediction These guys thrive in chaos—which is exactly what T20 cricket serves up.
To grow a cut bloom garden this year, yet you’re confounded and don’t have any idea how to begin choosing what to grow…Fashions Mag
If you are a student in Austria and struggling to finish your work, worry not. The Tutors Help is here to assist you step by step. If you need assistance in the area of research, writing, or even editing, our experts can be capable of assisting you.
We will assist you in saving time, lowering stress levels, and enhancing academic performance. Chat with The Tutors Assistance today and receive the perfect assignment assistance in Austria!
https://www.thetutorshelp.com/edu/assignment-help-in-austria.php
Assignment Help in Austria
I would like to sincerely thank you for sharing such valuable insights on this topic. Your content was not only informative but also very well-structured and easy to understand. It's great to see professionals like you contribute helpful resources to the industry. Looking forward to reading more from your blog! Apart from that, if you need any kind of information or services related to claims processing software, you can contact DataGenix. They provide the best and affordable services.
Great insights in this article! I’ve been exploring durable and cost-effective fencing solutions for a while, and recently came across RCC Readymade Compound Walls as a game-changer. Their quick installation and long-lasting strength make them a top choice for both residential and commercial properties.
If anyone’s looking for trusted Precast Compound Wall manufacturers in Ranchi, there are some really reliable options now offering quality products at competitive prices. Also, for landscaping or driveway projects, don’t overlook the value of partnering with a skilled Concrete Paver Block Manufacturer in Ranchi — their precision and design options can really elevate a space.
Informative article! Finding the best second hand cars in Kerala has become so much easier these days with trustworthy dealers and online platforms offering a wide range of options. Whether you're looking for fuel efficiency, style, or affordability, there’s something for everyone best second-hand cars in Kerala market.
It’s great to see more people considering pre-owned vehicles as a smart investment, especially when you can get top brands in excellent condition at a fraction of the price. Just make sure to check the vehicle history, service records, and get a proper inspection done before buying.
Really impressive breakdown—each section brings clarity to what to expect this season. Guwahati Spring League 2025 Schedule Loved the analytical depth.
Great insights into the upcoming cricket season! The player highlights make the predictions more precise.Emirates D50 2025 Schedule Excited to see how things unfold.
This isn’t just a prediction—it’s a full analysis. .MI vs SRH Dream11 Prediction IPL 2025Loved the way stats and form were used to back the points.
In today’s competitive manufacturing landscape, choosing the right supplier for high-performance components is crucial. A trusted Cold Forging Parts Manufacturer can provide exceptional strength and durability by shaping metal at room temperature, resulting in parts with excellent structural integrity and minimal material waste. Cold forging is especially ideal for automotive and industrial applications where reliability and volume production matter.
Equally important is working with a skilled Precision Machining Parts Manufacturer who can deliver components with tight tolerances and flawless finishes. Whether it's for aerospace, electronics, or medical devices, precision machining ensures every part meets exact specifications and industry standards.
Combining cold forging with precision machining opens up new possibilities for custom, high-strength parts that don’t compromise on accuracy. This blog does a great job highlighting how these manufacturing methods contribute to quality and efficiency.
Cipd Assignment Help
Achieve high scores with the best CIPD assignment help from The Tutors Help. Our expert writers specialize in CIPD modules and ensure your assignments are well-researched, structured, and aligned with academic standards. Whether you're pursuing we provide tailored support to meet your specific needs and deadlines. With our professional guidance, you’ll gain a deeper understanding of HR concepts and improve your academic performance. Trust The Tutors Help for plagiarism-free, original content and round-the-clock assistance. Get the edge you need to succeed in your CIPD journey—contact us today for reliable and affordable assignment support.
https://www.thetutorshelp.com/cipd-assignment-help.php
Cipd Assignment Help
AutoCad Assignment Help
Need help with your AutoCAD assignment or homework? Get expert guidance to master 2D and 3D drafting, modeling, and design. Whether you're a beginner or advancing your skills, professional AutoCAD tutors can help you understand complex commands, improve accuracy, and complete your projects on time. With step-by-step assistance, you'll learn to create precise technical drawings, architectural plans, and engineering models using industry-standard practices. Support is available for students at all levels, ensuring quality results and improved performance. Don’t stress over deadlines—get reliable AutoCAD assignment help and boost your grades with personalized support tailored to your learning needs.
https://www.thetutorshelp.com/autocad-assignment-help.php
AutoCad Assignment Help
Excellent article! It’s great to see the growing awareness and application of epoxy solutions in various industries. The demand for high-quality Epoxy Diluents in India has been steadily increasing, especially as manufacturers look for ways to fine-tune viscosity and improve the workability of epoxy formulations. Choosing the right diluent plays a critical role in achieving optimal performance and finish.
I’m also particularly interested in Flexible Dome Epoxy, which offers a perfect balance of strength and flexibility, making it ideal for applications like decals, labels, and electronics. It provides a clear, glossy finish while remaining resistant to cracking and yellowing.
Furthermore, Epoxy Flooring in India has gained popularity in both industrial and residential spaces for its durability, easy maintenance, and aesthetic appeal. It's great to see more builders and architects embracing this solution.
If you are a Salalah student having problems with assignments, fret not. The Tutors Help is here to ease your academic journey. With professional guidance, punctual delivery, and low rates, we are your guide to academic success.
Get in touch with us today and receive the best assignment assistance in Salalah—fast, convenient, and hassle-free!
https://www.thetutorshelp.com/edu/assignment-help-salalah.php
Assignment Help Salalah
As a Manama student searching for expert assignment assistance, The Tutors Help will be the best option. We are dedicated to guiding you through academic milestones with ease, free of fear. From school assignments to university dissertations, we have full assistance custom-made according to your requirements.
So why not? Let The Tutors Help ease your student life. Chat with us today and benefit from the best assignment assistance in Manama at competitive rates!
https://www.thetutorshelp.com/edu/assignment-help-manama.php
Assignment Help Manama
Excellent article! It’s great to see more attention being given to advanced manufacturing techniques and the importance of reliable suppliers. Choosing the right Cold Forging Parts Manufacturer plays a vital role in ensuring durability and strength in components, especially for industries that demand high-performance parts like automotive, construction, and heavy machinery. Cold forging offers exceptional material efficiency and reduced machining needs, making it a smart choice for cost-effective production. Equally important is working with a trusted Precision Machining Parts Manufacturer, as precision is everything when it comes to tight tolerances and complex geometries. These manufacturers bring expertise, state-of-the-art equipment, and a focus on quality that can make or break a project. This blog did a great job highlighting the key factors to consider when selecting manufacturing partners. I’m looking forward to more insights on how to streamline the supply chain with the right manufacturing solutions. Keep up the informative content!
A great preview of what’s to come! The emphasis on key players provides a clearer picture of potential outcomes. SRH vs MI Dream11 Prediction IPL 2025 Looking forward to tracking the action.
A detailed and engaging analysis! Highlighting key players provides great clarity. LSG vs DC Dream11 Prediction IPL 2025 Looking forward to keeping up with the action.
Great take on the season ahead! The player analysis adds depth to the predictions. Sanju Samson to Miss RCB vs RR Match Excited to track performances and key stats.
Well-structured preview! The focus on important players makes the predictions stand out. MS Dhoni About MI Loss Can’t wait to see how the matches play out.
In today’s fast-paced commercial and industrial environments, investing in advanced cleaning solutions is crucial. A trusted Automatic Electric Steam Generator Manufacturer in India provides high-efficiency steam solutions ideal for industries like hospitality, healthcare, food processing, and garment manufacturing. These electric steam generators offer energy-efficient performance, quick start-up, and consistent steam output, making them a must-have for operations requiring precision and hygiene.
Equally vital is choosing a reliable Carpet Cleaner Machine Manufacturer in India. With rising demand for deep cleaning in commercial and residential spaces, high-performance carpet cleaning machines help maintain cleanliness, remove deep-set dirt, and extend carpet life. Whether it's for hotels, offices, or cleaning service providers, having powerful, easy-to-use equipment makes all the difference.
When selecting these machines, always go for manufacturers known for quality engineering, durability, and responsive support. Investing in the right technology from trusted Indian manufacturers enhances operational efficiency and delivers long-term value.
These aren’t just predictions—they’re warnings to the other teams. KKR vs PBKS Match Prediction If these guys fire, it’s game over!
Great take on the season ahead! The player analysis adds depth to the predictions. CSK vs SRH Dream11 Prediction IPL 2025 Excited to track performances and key stats.
A well-balanced and thoughtful preview! The emphasis on crucial players makes the analysis more engaging.KL Rahul Nears IPL Record On Return To Lucknow Can’t wait to stay updated.
Really enjoyed this preview! The spotlight on key players adds an extra layer of excitement. KL Rahul Sends Dig At LSG Can’t wait to follow the season closely.
Engaging and well-researched insights! The key player mentions add valuable depth to the predictions.Iyer and Ishan Gain BCCI Central Contract Looking forward to following the matches.
Well-structured preview! The focus on important players makes the predictions stand out. MUL vs ISL Dream11 Prediction PSL Can’t wait to see how the matches play out.
Has anyone gotten Botox in Nürnberg? I’m curious if it’s really worth the investment. I’ve heard it can make a huge difference in terms of rejuvenation but want to know if the results are long-lasting or if the cost is justified. botox nürnberg
Great read! Chhattisgarh T20 2025 Schedule And Fixtures If these bowlers hit their rhythm, they could shut down even the biggest hitters in the format.
You’ve nailed the potential game-breakers—T20s are short, sharp, and unpredictable, Virat Kohli Career Stats And Overview but these players bring consistency.
Thoughtful and well-researched take on the season! The player focus brings more clarity to the predictions. DC vs KKR Dream11 Prediction IPL 2025 Looking forward to the matches.
Strong take on the upcoming season! The player analysis adds valuable insights. Indian Players Laud Vaibhav Suryavanshi Can’t wait to watch the action unfold.
If the predictions hold true, we’re in for a thrilling season. GT vs SRH Dream11 Prediction IPL 2025 Can definitely see those key players turning the tide.
Well-analyzed insights on the cricket season ahead! The focus on standout players makes it even more engaging. Can SRH Still Qualify For Playoffs In IPL 2025Excited to see how things unfold.
Crisp and clear insights! Highlighting standout performers brings more depth to the predictions. KKR vs RR Dream11 Prediction IPL 2025 Eager to see how the season progresses.
Informative and well-thought-out! The player analysis makes the predictions more accurate. MI vs GT Dream11 Prediction IPL 2025 Looking forward to following their performances.
A brilliant take on the season ahead! The emphasis on standout players provides great clarity. SRH vs DC Dream11 Prediction IPL 2025 Looking forward to seeing their impact.
India's hygiene product industry is growing rapidly, with a strong focus on quality and innovation. A leading Baby Diaper manufacturer in India is dedicated to creating skin-friendly, highly absorbent diapers that ensure comfort and protection for infants. These manufacturers are constantly evolving to meet the needs of modern parenting.
Alongside baby care, the rise of Period Panty manufacturing in India reflects a shift towards sustainable and convenient menstrual hygiene solutions. These reusable, leak-proof panties are gaining popularity for their comfort and eco-friendliness.
Equally important is the role of an Adult Diaper manufacturer in India, offering dignity and mobility to elderly and differently-abled individuals. With advancements in materials and design, adult diapers now offer superior absorbency and comfort.
Together, these sectors represent a strong commitment to hygiene, care, and innovation. India continues to emerge as a reliable source for high-quality hygiene products across age groups and personal needs.
Really thoughtful post! As a parent, I’m always on the lookout for helpful resources that support children's growth and well-being. I recently came across kidsomia, and it offers some amazing tools and content designed specifically for kids. Definitely worth checking out if you're looking to enrich your child’s daily routine with fun and educational experiences!
https://kidsomia.com/
I've been exploring various online betting platforms, and Kheloyar really stands out for its user-friendly interface and quick payouts. The Kheloyar login process is super smooth, and I appreciate how secure and hassle-free it is. Whether you're into sports betting or live casino games, Kheloyar has something for everyone. Highly recommended for both beginners and seasoned players!
Know More:https://kheloyar.org.in/
I've been using Lotus365 for a few weeks now, and the experience has been great so far! The platform is smooth, secure, and offers a wide variety of games and betting options. The Lotus365 app makes it even more convenient to play on the go. Highly recommend it for anyone looking for a reliable and fun online gaming experience!
Know More:https://lotuusss365.org/
Reddy Book is an outstanding platform for online betting enthusiasts! Its intuitive interface and secure features make betting and account management a breeze. My experience with Reddybook has been exceptional, thanks to its easy navigation and real-time updates on live events. If you're looking for a dependable and exciting betting platform, Reddy Anna Book is definitely worth checking out!
Know More: https://reddyannabook.social/
India is rapidly emerging as a leading provider of advanced garment finishing equipment. As a trusted Vacuum Ironing Table Manufacturer in India, companies here are offering efficient and ergonomic solutions ideal for tailoring units, garment factories, and laundry services. These tables ensure faster ironing and a crisp finish, boosting productivity. Additionally, being a top Steam Generator Manufacturer in India, the country supplies high-performance steam systems that are essential for consistent heat and steam delivery in industrial applications. These generators are built for durability and energy efficiency. Furthermore, as a reliable Steam Press Industrial Manufacturer in India, Indian manufacturers are delivering robust and user-friendly presses that meet global standards. Their machines are widely used in textile, laundry, and garment sectors. With a strong focus on quality, innovation, and customer support, Indian manufacturers are becoming the go-to choice for businesses looking to upgrade their garment care and finishing operations.
Delhi has become a key manufacturing hub for high-quality surgical and operating room equipment, meeting the demands of modern healthcare facilities. As a leading Orthopedic Attachment Manufacturer in Delhi, companies in the region provide robust and adaptable solutions that enhance the functionality of surgical tables, particularly in orthopedic procedures. These attachments support precision, stability, and patient safety. Additionally, Delhi is known as a top Ceiling LED OT Light Manufacturer in Delhi, offering advanced lighting systems designed for efficient ceiling mounting, providing surgeons with clear, shadow-free illumination. The city also excels as a LED Surgical Light Manufacturer in Delhi, producing energy-efficient, long-lasting lights that are critical for optimal visibility in operating rooms. Moreover, as a prominent Electro OT Table Manufacturer in Delhi, local manufacturers are delivering electrically operated tables with advanced controls, ensuring seamless patient positioning and surgical workflow. Together, these innovations highlight Delhi’s vital role in the growth of India’s medical equipment industry.
Post a Comment