×

First time here?

You are looking at the most recent posts. You may also want to check out older archives. Please leave a comment, ask a question and consider subscribing to the latest posts via RSS or email. Thank you for visiting!

Sometimes I think reading materials get overlooked in SDKs and we miss some hidden gems.  One such gem I’d like to bring to your attention is the ability to add some subtle styling to an AutoCompleteBox from the Silverlight Toolkit to provide you with a cheap version of an editable ComboBox.

Sure Silverlight 2 has a ComboBox as part of the core controls now, but as I’ve previously noted, the ComboBox in current form exhibits only DropDownList behaviors.  I’m sure this will likely change with future versions, but if you have a need for an editable ComboBox feel, here’s a start.

If you think about the AutoCompleteBox functionality, it provides a list of items that are filtered when the user starts typing in there.  Well, that’s one function of a ComboBox right?  The other exhibited behavior we need is to be able to click to activate the DropDownList functionality and select.  Here’s where styling comes in (with a little help from some properties on AutoCompleteBox as well).

Let’s start by adding the items we’ll be dealing with: AutoCompleteBox and a data class (I’ll use a local hard-coded data class for portability in this code).  To use the AutoCompleteBox, make sure you’ve downloaded the Silverlight Toolkit and then add a reference in your Silverlight project to Microsoft.Windows.Controls.dll.  Then add the xmlns decoration in your UserControl…here’s mine (I use “toolkit”):

   1: <UserControl x:Class="ACBEditCombo.Page"
   2:     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   3:     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   4:     xmlns:toolkit="clr-namespace:Microsoft.Windows.Controls;assembly=Microsoft.Windows.Controls"
   5:     Width="400" Height="300">
   6:     <Grid x:Name="LayoutRoot" Background="White">
   7:         <toolkit:AutoCompleteBox MinimumPrefixLength="0" 
   8:                                  MinimumPopulateDelay="200" 
   9:                                  x:Name="FruitChoice"
  10:                                  Width="200" Height="25" />
  11:     </Grid>
  12: </UserControl>

Here’s the Fruit class I’ll be using:

   1: #region Fruit Class
   2:     public class Fruit
   3:     {
   4:         public string Name { get; set; }
   5:         public override string ToString()
   6:         {
   7:             return this.Name;
   8:         }
   9:  
  10:         public static List<Fruit> GetFruitChoices()
  11:         {
  12:             List<Fruit> choices = new List<Fruit>();
  13:  
  14:             choices.Add(new Fruit() { Name = "Apple" });
  15:             choices.Add(new Fruit() { Name = "Apricot" });
  16:             choices.Add(new Fruit() { Name = "Banana" });
  17:             choices.Add(new Fruit() { Name = "Orange" });
  18:             choices.Add(new Fruit() { Name = "Pineapple" });
  19:             choices.Add(new Fruit() { Name = "Mango" });
  20:             choices.Add(new Fruit() { Name = "Papaya" });
  21:             choices.Add(new Fruit() { Name = "Pumpkin" });
  22:  
  23:             return choices;
  24:         }
  25:     }
  26:     #endregion

As you can see it is simple, but I wanted to make sure I was using more than just a string (yes I know essentially it is an object with only a string, but think outside the box :-)).  Now we can wire up this code here to get our AutoCompleteBox behavior working:

   1: public partial class Page : UserControl
   2: {
   3:     List<Fruit> choices = Fruit.GetFruitChoices();
   4:  
   5:     public Page()
   6:     {
   7:         InitializeComponent();
   8:         Loaded += new RoutedEventHandler(Page_Loaded);
   9:     }
  10:  
  11:     void Page_Loaded(object sender, RoutedEventArgs e)
  12:     {
  13:         FruitChoice.ItemsSource = choices;
  14:         FruitChoice.ItemFilter = (prefix, item) =>
  15:             {
  16:                 if (string.IsNullOrEmpty(prefix))
  17:                 {
  18:                     return true;
  19:                 }
  20:  
  21:                 Fruit f = item as Fruit;
  22:  
  23:                 if (f == null)
  24:                 {
  25:                     return false;
  26:                 }
  27:  
  28:                 return f.Name.ToLower().Contains(prefix.ToLower());
  29:             };
  30:     }
  31: }

Here we are using the same ItemFilter method I noted previously about AutoCompleteBox.  Once we have this when we start typing we’ll get:

Now all we need to do is make it look and act also like a ComboBox.  Here we can take styles and apply them.  We’re going to do three things using Style resources:

    1. Modify the control template for our toolkit:AutoCompleteBox to include a ToggleButton
    2. Create a style for the ToggleButton that looks like an arrow to cue the user what to do with it
    3. Style the list displayed a little bit

Best of all – we’re not going to change any of our logic code.  None.  First let’s modify the control template.  I’m putting these in my App.xaml resources so my app could use them globally.  Here’s the full style for the new control template which has new content in there and a ToggleButton added (I’ll keep it collapsed here for the sake of making this post less verbose than it already is):

   1: <Style x:Key="EditableComboStyle" TargetType="toolkit:AutoCompleteBox">
   2:             <Setter Property="SearchMode" Value="StartsWith" />
   3:             <Setter Property="Background" Value="#FF1F3B53"/>
   4:             <Setter Property="IsTabStop" Value="False" />
   5:             <Setter Property="HorizontalContentAlignment" Value="Left"/>
   6:             <Setter Property="BorderBrush">
   7:                 <Setter.Value>
   8:                     <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
   9:                         <GradientStop Color="#FFA3AEB9" Offset="0"/>
  10:                         <GradientStop Color="#FF8399A9" Offset="0.375"/>
  11:                         <GradientStop Color="#FF718597" Offset="0.375"/>
  12:                         <GradientStop Color="#FF617584" Offset="1"/>
  13:                     </LinearGradientBrush>
  14:                 </Setter.Value>
  15:             </Setter>
  16:             <Setter Property="Template">
  17:                 <Setter.Value>
  18:                     <ControlTemplate TargetType="toolkit:AutoCompleteBox">
  19:                         <Grid Margin="{TemplateBinding Padding}">
  20:                             <VisualStateManager.VisualStateGroups>
  21:                                 <VisualStateGroup x:Name="PopupStates">
  22:                                     <VisualStateGroup.Transitions>
  23:                                         <VisualTransition GeneratedDuration="0:0:0.1" To="PopupOpened" />
  24:                                         <VisualTransition GeneratedDuration="0:0:0.2" To="PopupClosed" />
  25:                                     </VisualStateGroup.Transitions>
  26:                                     <VisualState x:Name="PopupOpened">
  27:                                         <Storyboard>
  28:                                             <DoubleAnimation Storyboard.TargetName="PopupBorder" Storyboard.TargetProperty="Opacity" To="1.0" />
  29:                                         </Storyboard>
  30:                                     </VisualState>
  31:                                     <VisualState x:Name="PopupClosed">
  32:                                         <Storyboard>
  33:                                             <DoubleAnimation Storyboard.TargetName="PopupBorder" Storyboard.TargetProperty="Opacity" To="0.0" />
  34:                                         </Storyboard>
  35:                                     </VisualState>
  36:                                 </VisualStateGroup>
  37:                             </VisualStateManager.VisualStateGroups>
  38:                             <TextBox IsTabStop="True" x:Name="Text" Style="{TemplateBinding TextBoxStyle}" Margin="0" />
  39:                             <ToggleButton 
  40:                                 x:Name="DropDownToggle" 
  41:                                 HorizontalAlignment="Right"
  42:                                 VerticalAlignment="Center"
  43:                                 Style="{StaticResource ComboToggleButton}"
  44:                                 Margin="0"
  45:                                 HorizontalContentAlignment="Center" 
  46:                                 Background="{TemplateBinding Background}" 
  47:                                 BorderThickness="0" 
  48:                                 Height="16" Width="16"
  49:                                 >
  50:                                 <ToggleButton.Content>
  51:                                     <Path x:Name="BtnArrow" Height="4" Width="8" Stretch="Uniform" Data="F1 M 301.14,-189.041L 311.57,-189.041L 306.355,-182.942L 301.14,-189.041 Z " 
  52:                                           Margin="0,0,6,0" HorizontalAlignment="Right">
  53:                                         <Path.Fill>
  54:                                             <SolidColorBrush x:Name="BtnArrowColor" Color="#FF333333"/>
  55:                                         </Path.Fill>
  56:                                     </Path>
  57:                                 </ToggleButton.Content>
  58:                             </ToggleButton>
  59:                             <Popup x:Name="Popup">
  60:                                 <Border x:Name="PopupBorder" HorizontalAlignment="Stretch" Opacity="0.0" BorderThickness="0" CornerRadius="3">
  61:                                     <Border.RenderTransform>
  62:                                         <TranslateTransform X="2" Y="2" />
  63:                                     </Border.RenderTransform>
  64:                                     <Border.Background>
  65:                                         <SolidColorBrush Color="#11000000" />
  66:                                     </Border.Background>
  67:                                     <Border HorizontalAlignment="Stretch" BorderThickness="0" CornerRadius="3">
  68:                                         <Border.Background>
  69:                                             <SolidColorBrush Color="#11000000" />
  70:                                         </Border.Background>
  71:                                         <Border.RenderTransform>
  72:                                             <TransformGroup>
  73:                                                 <ScaleTransform />
  74:                                                 <SkewTransform />
  75:                                                 <RotateTransform />
  76:                                                 <TranslateTransform X="-1" Y="-1" />
  77:                                             </TransformGroup>
  78:                                         </Border.RenderTransform>
  79:                                         <Border HorizontalAlignment="Stretch" Opacity="1.0" Padding="2" BorderThickness="2" BorderBrush="{TemplateBinding BorderBrush}" CornerRadius="3">
  80:                                             <Border.RenderTransform>
  81:                                                 <TransformGroup>
  82:                                                     <ScaleTransform />
  83:                                                     <SkewTransform />
  84:                                                     <RotateTransform />
  85:                                                     <TranslateTransform X="-2" Y="-2" />
  86:                                                 </TransformGroup>
  87:                                             </Border.RenderTransform>
  88:                                             <Border.Background>
  89:                                                 <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
  90:                                                     <GradientStop Color="#FFDDDDDD" Offset="0"/>
  91:                                                     <GradientStop Color="#AADDDDDD" Offset="1"/>
  92:                                                 </LinearGradientBrush>
  93:                                             </Border.Background>
  94:                                             <ListBox x:Name="SelectionAdapter" ScrollViewer.HorizontalScrollBarVisibility="Auto" ScrollViewer.VerticalScrollBarVisibility="Auto" ItemTemplate="{TemplateBinding ItemTemplate}" />
  95:                                         </Border>
  96:                                     </Border>
  97:                                 </Border>
  98:                             </Popup>
  99:                         </Grid>
 100:                     </ControlTemplate>
 101:                 </Setter.Value>
 102:             </Setter>
 103:         </Style>

Now if you look you’ll see that the ToggleButton itself has a Style attribute, so here’s the Style we use for that:

   1: <Style x:Name="ComboToggleButton" TargetType="ToggleButton">
   2:             <Setter Property="Foreground" Value="#FF333333"/>
   3:             <Setter Property="Background" Value="#FF1F3B53"/>
   4:             <Setter Property="Padding" Value="0"/>
   5:             <Setter Property="Template">
   6:                 <Setter.Value>
   7:                     <ControlTemplate TargetType="ToggleButton">
   8:                         <Grid>
   9:                             <Rectangle Fill="Transparent" />
  10:                             <ContentPresenter
  11:                             x:Name="contentPresenter"
  12:                             Content="{TemplateBinding Content}"
  13:                             ContentTemplate="{TemplateBinding ContentTemplate}"
  14:                             HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
  15:                             VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
  16:                             Margin="{TemplateBinding Padding}"/>
  17:                         </Grid>
  18:                     </ControlTemplate>
  19:                 </Setter.Value>
  20:             </Setter>
  21:         </Style>

Now the only thing we need to do is add the Style attribute for our AutoCompleteBox as reflected here (notice the added Style attribute):

   1: <UserControl x:Class="ACBEditCombo.Page"
   2:     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   3:     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   4:     xmlns:toolkit="clr-namespace:Microsoft.Windows.Controls;assembly=Microsoft.Windows.Controls"
   5:     Width="400" Height="300">
   6:     <Grid x:Name="LayoutRoot" Background="White">
   7:         <toolkit:AutoCompleteBox MinimumPrefixLength="0" 
   8:                                  MinimumPopulateDelay="200" 
   9:                                  x:Name="FruitChoice"
  10:                                  Width="200" Height="25"
  11:                                  Style="{StaticResource EditableComboStyle}"/>
  12:     </Grid>
  13: </UserControl>

And now when we look at our application running we have what looks to be an editable ComboBox:

The ComboBox behavior is enabled now via the ToggleButton and the MinimumPrefixLength attribute on the AutoCompleteBox (try changing it to 1 and you’ll see that you don’t get exactly the same behavior).

It’s little gems like this that should cause you to pay attention to the finer details of SDKs, samples, etc.  I hope you found this helpful…if you have, please consider subscribing for more samples like this (and no I’m not planning on just emitting all the SDK samples :-)).  You can download my code for this above in a complete solution here: ACBEditCombo.zip.


This work is licensed under a Creative Commons Attribution By license.


11/5/2008 5:16 PM | # re: Use Styles for an editable Silverlight ComboBox
Tim,

This is a very clever implementation. Thanks
11/6/2008 3:28 AM | # re: Use Styles for an editable Silverlight ComboBox
Very Nice. Few days back, I was thinking of achieving a combo-box like behavior using an AutoCompleteBox and today I saw this post. Great work, Tim.
11/6/2008 6:50 AM | # re: Use Styles for an editable Silverlight ComboBox
Hi Tim,

Nice work. Should the downloaded sample load into Visual Web Developer Express (or Visual C# Express)? I'm seeing a "project type not supported error".

Thanks,
Martin
11/6/2008 8:29 AM | # re: Use Styles for an editable Silverlight ComboBox
Martin: This would be Web Dev Express 2008 SP1 with the Silverlight Tools installed.
11/6/2008 4:09 PM | # re: Use Styles for an editable Silverlight ComboBox
Hi Tim,

Apologies. I just retried - the problem was caused by launching the .csproj file from Windows Explorer; it loaded into VS2005 (also on the machine) - hence the problem.

By starting Web Dev Express 2008 SP1 (with the Silverlight Tools installed), then using "File/Open Project..." it now loads cleanly.

Thanks for checking.

Martin

11/13/2008 2:22 AM | # re: Use Styles for an editable Silverlight ComboBox
Hi Tim,
First of all,indeed very clever implementation. Thanks.

One question: I'm using AutoCompleteBox control with your styles and it is working fine, except the following:
When item was selected, the list can't open by clicking on the togglebutton.
Do you have any idea what is the reason for that?

Thanks,
Yariv
11/13/2008 7:59 AM | # re: Use Styles for an editable Silverlight ComboBox
Yariv. Yikes, didn't see that before. Let me check why it is doing that...thanks for pointing this out.
11/14/2008 10:49 AM | # re: Use Styles for an editable Silverlight ComboBox
Mudassir/Yariv: I'm looking into it.
11/15/2008 10:51 PM | # re: Use Styles for an editable Silverlight ComboBox
Added this line to your EditableComboStyle style and the toggle button seems to work.



Regards,
Sandy Place
11/15/2008 10:54 PM | # re: Use Styles for an editable Silverlight ComboBox
Whoops sorry the comment somehow it ate my xaml. trying again...

At the top of the EditableComboStyle style add in angle brackets:

Setter Property="MinimumPrefixLength" Value="0"
12/12/2008 3:03 AM | # re: Use Styles for an editable Silverlight ComboBox
Hi Tim,

First, thank you very much for all your samples. I am working with silverlight since several months and I can say you that it is not the first time that I come here to take some part of your source code like a sample :)

Of course I am working on different components which can be shared or partially shared in the future (like a paginable /auto generable filters datagrid).

Now I am working on this "auto generable" filter and I thought in put inside a combo to like a one of the different filter types.

When I saw the sample from silverlight.net I became really happy but after I saw you sample and it was much better for me. The problem is the ToggleButton :( It doesn't work when I click on it...

I saw some people have the same problem... Do you know how to fix it?

I reviewed the source code from silverlight.net and I compared it with your sample and I didn't undestand why the togglebutton doesn't work :(

Thank you very much for your attention,

Best regards,

Alex
12/12/2008 3:24 AM | # solution?
Hi Tim,

I have a solution but when I try to paste and publish the comment here I have received an alert error from the server :(

If do you know how can I send the solution I will can share it with you :)

Best regards,

Alex
12/12/2008 7:01 AM | # re: Use Styles for an editable Silverlight ComboBox
Alex: if you have a solution that's great -- others have emailed me solutions as well. I'm not sure if the new AutoCompleteBox released this week updates the problem as well.
12/15/2008 6:59 AM | # re: Use Styles for an editable Silverlight ComboBox
Hi, Tim and Alex, any updates about above mentioned issue(ToggleButton not work), i added in the , seems like the togglebutton worked but, when i input something, it doesn't work. could you please email me the more better solutions? thanks so much:)
Gravatar
12/15/2008 3:26 PM | # re: Use Styles for an editable Silverlight ComboBox
Hello Fellas,

Tim is right, the new December 2008 Silverlight Toolkit update does the magic on the Autocomplete Combobox, and it fixed that Issue that we were talking about here in this blog.

I confirmed, just updated the reference to the new binaries and it works.

Thank you once again Mr. Tim.

Take Care,

Mudassir Azeemi
San Francisco, CA
12/19/2008 12:43 PM | # re: Use Styles for an editable Silverlight ComboBox
Works fine except once I add the style to app.xaml, I can no longer see my controls in the xaml preview.

I get the following error.
Invalid attribute value toolkit:AutoCompleteBox for property TargetType.

I have set the namespaces just like the example and added the reference, did I miss something.

12/26/2008 3:00 AM | # re: Use Styles for an editable Silverlight ComboBox
Hi Tim,

I used this implementation inside CellEditingTemplate for my DataGrid column and it works great. The only thing it lacks is it does not automatically selects the item (I want it to automatically select the item currently displayed in the DataGrid cell). I cannot force it since AutoCompleteBox.SelectedItem property is read only. Any suggestions on this?

Regards,
Syed Mehroz Alam
1/5/2009 3:46 AM | # re: Use Styles for an editable Silverlight ComboBox
Hi everybody. I have two questions about this control:

How can I "get" the autocompletebox's togglebutton? (DropDownToggle)

How can I modify the text of the Textbox when the user clicks on the togglebutton? I want to define this event as a template event.

Thanks
1/15/2009 1:49 AM | # re: Use Styles for an editable Silverlight ComboBox
Hi Tim,
Great code, thanks a lot.

I am facing the same problem than Joe in terms of the "Invalid attribute value controls:AutoCompleteBox for property TargetType" error. I am pulling my hair out, on another solution I can view the page in VS2008, but on this project it gives me the error. When I run it, everything works fine, so I am totally puzzled. When I open the .XAML file in Blend, I do not get an error.
I double checked all the anmespaces and references.

In APP.XAML I have the following :
<Application xmlns="schemas.microsoft.com/.../presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:controls="clr-namespace:Microsoft.Windows.Controls;assembly=Microsoft.Windows.Controls"
>

When I open ANY page that uses the autocomplete style, I am getting the said error with reference to this code in APP,XAML:
<Style x:Key="EditableComboStyle" TargetType="controls:AutoCompleteBox">

I can see no reason for the error, as the "controls" part is referenced in the xmnls section, and the project runs.

Has anyone else experienced this behaviour and how did you resolve it ?

Kind regards
Anton.
1/17/2009 2:38 PM | # re: Use Styles for an editable Silverlight ComboBox
How to use AutoComplete combobox in DataGrid ? Is there any code sample about editing data in DataGrid using ComboBox ?
1/19/2009 3:41 AM | # re: Use Styles for an editable Silverlight ComboBox
I was just thinking about Use Styles for an editable Silverlight ComboBox and you’ve really helped out. Thanks!
1/26/2009 3:24 PM | # re: Use Styles for an editable Silverlight ComboBox
It seems that if you change the Text property rapidly (programatically), the Popup element is open when the control is loaded. Any ideas on how to prevent this?
3/30/2009 10:22 AM | # re: Use Styles for an editable Silverlight ComboBox
I encountered the following issues:

1. One Tab key press is ignored. Tab must pressed two times to move to other field.

2. Text covers button. If Text width is greater that TextBox width, Toggle button is not visible.

3. MinimumPopulateDelay occurs after toggle button is clicked and before dropdown list is opened.

4. Sometimes clicking toggle button does not open dropdown list. Using MinimumPrefixLength="0" as suggested in comments here does not fix this.

5. If Enter is pressed, UserControl Keydown event does not occur. Adding Keydown event handler to control does not fix this. It is not possible to catch enter press if AutocompleteCombo is active.

How to fix those issues ?
4/6/2009 10:05 AM | # re: Use Styles for an editable Silverlight ComboBox
To allow Text reset from event handlers in case of wrong entry, I added Text="{TemplateBinding Text}" to template:

<TextBox Text="{TemplateBinding Text}" ....
7/21/2009 1:03 AM | # Silverlight 3
Hi,

I am trying to use this control in Silverlight 3 application, but I have problems with it - clicking on button do nothing...
Any workarounds?

Thanks for answer,

Tomas
7/21/2009 9:07 AM | # re: Use Styles for an editable Silverlight ComboBox
tomasK - take a look at the updated AutoCompleteBox in the toolkit release for July 2009 -- i believe it has been updated to support more scenarios.
7/21/2009 11:28 AM | # re: Use Styles for an editable Silverlight ComboBox
-I forgot to say that already using AutoCompleteBox from the toolkit release for July 2009, so now I dont know what to do or change for correct behavior...
Gravatar
7/22/2009 12:18 PM | # re: Use Styles for an editable Silverlight ComboBox
I'm having the same issue as tomas, need to update this for SL3 and the latest toolkit.
7/23/2009 6:05 AM | # re: Use Styles for an editable Silverlight ComboBox
I' got the same problem, after upgrade to July'09 realese popup doesn't fill itself with suggestions. Does anyone an idea how to fix it ?
7/24/2009 11:06 AM | # re: Use Styles for an editable Silverlight ComboBox
Hello, thanks for pointing out this interesting approach.

I'm using System.Windows.Controls.AutoCompleteBox from SL3, and
the ToggleButton didn't work for me either.

I appended the following Attribute to the ToggleButton("DropDownToggle"):

IsChecked="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=IsDropDownOpen, Mode=TwoWay}"

This kind of worked, so maybe it helps someone else, too.
I'm not that happy with the delay though, so it'd be great if anyone more experienced pointed out a better way.
7/26/2009 2:41 AM | # re: Use Styles for an editable Silverlight ComboBox
I placed this to a DataGrid column, added Khyalis suggestion nad code from SL3 breaking changes document.

If text is selected, dropdown button is ignored: after setting
acb.IsDropDownOpen = !acb.IsDropDownOpen;

populating event is *not* called and popup remains closed.

Only if text in combo is not selected, dropdown opens menu. How to fix this ?

DataGrid columns are created dynamically:

templateCol.CellEditingTemplate = XamlReader.Load(string.Format(@"<DataTemplate
xmlns='schemas.microsoft.com/winfx/2006/xaml/presentation'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
xmlns:local='clr-namespace:MyApp.Controls;assembly=MyApp'
>
<local:AutoCompleteBoxBase
Text=""{{Binding {0}, Mode=TwoWay,ValidatesOnExceptions='True',NotifyOnValidationError='True'}}""
Style=""{{StaticResource EditableComboStyle}}""
MinimumPrefixLength=""0""
IsTextCompletionEnabled=""True""
FilterMode=""None""
MinimumPopulateDelay=""1000""
Padding='0,0'
>
</local:AutoCompleteBoxBase>
</DataTemplate>",
"MyProperty"
)) as DataTemplate;

My combobox base class:

using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace MyApp.Controls {

public class AutoCompleteBoxBase : AutoCompleteBox
{
public ComboBoxViewModel ViewModel { get; set; }
TextBox _text;

public override void OnApplyTemplate()
{
base.OnApplyTemplate();
_text = GetTemplateChild("Text") as TextBox;
_text.SelectionChanged += new RoutedEventHandler(_text_SelectionChanged);

}

protected override void OnPopulating(PopulatingEventArgs e)
{
base.OnPopulating(e);
if (e.Parameter == null)
return;
ViewModel.Populate(this, e.Parameter);
e.Cancel = true;
}


protected override void OnLostFocus(RoutedEventArgs e)
{
base.OnLostFocus(e);
if (SelectedItem == null)
Text = "";
ViewModel.WriteValue(this);
}

protected override void OnDropDownClosed(RoutedPropertyChangedEventArgs<bool> e)
{
base.OnDropDownClosed(e);
ViewModel.WriteValue(this);
}

void _text_SelectionChanged(object sender, RoutedEventArgs e)
{
if (FocusManager.GetFocusedElement() != _text && _text.SelectionStart != 0)
_text.SelectionStart = 0;
}
}
}


7/31/2009 2:37 AM | # re: Use Styles for an editable Silverlight ComboBox
Hi, Tim..
I have integrated your sample to Silverlight 3. The problem I am facing after that is, the intellisense drop down is not expanding. Actually it get displayed below the TextBox but does not showing any data in it.
Gravatar
8/17/2009 1:17 PM | # re: Use Styles for an editable Silverlight ComboBox
Any update on a fix for showing the data in the dropdown? It would be really helpful to get an updated sample.
Gravatar
8/17/2009 1:32 PM | # re: Use Styles for an editable Silverlight ComboBox
For those interested a relatively complete fix can be found here:

stackoverflow.com/.../fixing-tim-heuers-editabl...
8/28/2009 3:07 PM | # re: Use Styles for an editable Silverlight ComboBox
IsTabStop=false on the AutoCompleteBox will fix the tab issue.
The TextBox (inside the AutoCompleteBox template) will still get focus on tab.

12/2/2009 10:05 AM | # re: Use Styles for an editable Silverlight ComboBox
thanks Mark. I finally able to work it on SL 4.0 Beta
12/13/2010 9:54 PM | # re: Use Styles for an editable Silverlight ComboBox
Has anyone got this to work in Silverlight 4? Or does the ComboBox now support edits in Silverglith 4?

I upgraded Tim's attached project to VS2010, and the toggle button doesn't work and nothing appears in the popup when typing in the field. The list is always empty.
2/18/2011 1:24 AM | # re: Use Styles for an editable Silverlight ComboBox
the toggle button doesn't work and nothing appears in the popup when typing in the field. The list is always empty. (silverlight 3 and VS 2008)
2/18/2011 5:22 AM | # AutocompleteBox selected text
Hi,

I have an autocompletebox in my page and I am facing an issue. If the length of the items is long then after selecting an item from the list, the selected item will be displayed from the end. For example if I selected
"I am trying to learn Silverlight"

then the box will display "to learn Silverlight". In order to see the text from the starting user will have to do it manually.

I want the selected item to be shown from the starting e.g.
"I am trying to learn" and to see the remaining part user can do it manually.

Please help.

Thanks,
Gaurav
1/11/2012 3:25 AM | # re: Use Styles for an editable Silverlight ComboBox
Hi,

I tried yours and JC's approach but none of them work in silverlight 4.0/ VS 2010. It'll be really helpful if you can post an update to this for silverlight 4.
4/24/2012 4:43 AM | # re: Use Styles for an editable Silverlight ComboBox
Hi,

I'am using Silverlight 3 in Visual Studio 2010 (SP1).
Using System.Windows.Controls.AutoCompleteBox

I needed to change <Setter Property="SearchMode" Value="StartsWith" /> to <Setter Property="FilterMode" Value="StartsWith" />

The dropdownbutton only worked after adding
IsChecked="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=IsDropDownOpen, Mode=TwoWay}"
to ToggleButton.

But the dropdown only shows 2 millimeter height: you cannot see the dropdownitems. Do you know the solution for this?
4/24/2012 4:58 AM | # re: Use Styles for an editable Silverlight ComboBox
I found the solution fo this:

I had to change the name of the listbox:
<ListBox x:Name="SelectionAdapter" to <ListBox x:Name="Selector"
Now it seems to work!
7/16/2012 6:32 AM | # re: Use Styles for an editable Silverlight ComboBox
Marcel, thanks for the update, yes those 3 things fixed my issues also with he drop down not working. Solution needs to be udpated to SL4.

 
Please add 3 and 5 and type the answer here:

DISCLAIMER:

The opinions/content expressed on this blog are provided "ASIS" with no warranties and are my own personal opinions/content (unless otherwise noted) and do not represent my employer's view in any way.