Ok so I'm about half way through the development of the new xLite Player (Silverlight 3 media player) and I wanted to implement the AutoCompleteBox from the Silverlight Toolkit. I checked out the example on the Silverlight Toolkit site, but found it a bit difficult to follow. So this is how I ended up using the AutoCompleteBox for search suggestions. This actually provides search suggestions from an XML file. Here is the technology involved:
- Visual Studio 2008
- Expression Blend 3 Preview
- Silverlight 3 Beta
- Silverlight 3 Toolkit
- WCF
As typical me, here is the code that makes this works. I trimmed out all the rest just to focus on the AutoCompleteBox itself
XAML MARKUP
<input:AutoCompleteBox Height="25" Margin="5,17,5,12" Width="166" x:Name="txtSearchBox" />
XAML.cs CODE BEHIND
public MainPage()
{
Loaded += new RoutedEventHandler(MainPage_Loaded);
}
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
txtSearchBox.Populating += new PopulatingEventHandler(txtSearchBox_Populating);
}
private void txtSearchBox_Populating(object sender, PopulatingEventArgs e)
{
// Allow us to wait for the response
e.Cancel = true;
//only query web service if more than 3 chars
if (txtSearchBox.Text.Length >= 3)
{
// Create a request for suggestion
proxy.GetSuggestionsCompleted += new EventHandler<xLitePlayer2.xLitePlayerSvc.GetSuggestionsCompletedEventArgs>(proxy_GetSuggestionsCompleted);
proxy.GetSuggestionsAsync(txtSearchBox.Text);
}
}
private void proxy_GetSuggestionsCompleted(object sender, xLitePlayer2.xLitePlayerSvc.GetSuggestionsCompletedEventArgs e)
{
List<XElement> searchResults = new List<XElement>(e.Result);
List<string> data = new List<string>();
foreach (XElement ele in searchResults)
{
data.Add(ele.Element("mediaName").Value);
}
txtSearchBox.ItemsSource = data;
txtSearchBox.PopulateComplete();
}
WCF SERVICE METHOD
public List<XElement> GetSuggestions(string prefixText)
{
DataSet dsMedia = new DataSet();
dsMedia.ReadXml(System.Configuration.ConfigurationManager.AppSettings["xLitePlayerDataPath"].ToString());
XDocument xDoc = XDocument.Parse(dsMedia.GetXml());
var results = from n in xDoc.Descendants("mediaPath")
where (bool)n.Element("mediaName").Value.ToLower().Contains(prefixText.ToLower())
select n;
return results.ToList();
}
Now I'll probably end up changing this later but this is what was working for me last night. Well I hope this simple example helps those out just learning about the AutoCompleteBox like I just did.