Binding a Silverlight DataGrid’s ComboBox

Binding a Silverlight DataGrid’s ComboBox

by JBrooks 6. May 2011 07:13

Some things in Silverlight seem harder than they should be.  Binding a list of strings to a combobox is one such thing.  This involves the following steps to do a simple bind.

1. Have a private list of the strings in your page code.

 
private List<string> FuelList = new List<string>()
         {
             "OIL",
             "GAS",
             "COAL"
         };
 

2. In your initialization method add the list as a resource so your XAML can use it.  This must be done before the InitializeComponent(); call.

 
        public ucMyUserControl()
        {
            this.Resources.Add("FuelList", FuelList);
 
            InitializeComponent();
        }

 

3. Then you can reference the list as the source to you combo box.

<sdk:DataGrid AutoGenerateColumns="False"  MinHeight="130" Name="dgMyDataGrid" 
    ItemsSource="{Binding Path=ScheduleRows, Mode=TwoWay}"  
        CurrentCellChanged="dgMyDataGrid_CurrentCellChanged">
 
 
  <sdk:DataGrid.Columns>
     <sdk:DataGridTemplateColumn  Header="Fuel Type">
         <sdk:DataGridTemplateColumn.CellTemplate>
             <DataTemplate>
                  <TextBlock Margin="2" VerticalAlignment="Center"  
            HorizontalAlignment="Left" Text="{Binding FUEL_TYPE}" Width="120" />
             </DataTemplate>
             </sdk:DataGridTemplateColumn.CellTemplate>
                  <sdk:DataGridTemplateColumn.CellEditingTemplate>
                     <DataTemplate>
                         <ComboBox Height="23" Name="cbxFuelType" 
                                 ItemsSource="{StaticResource FuelList}"
                                 SelectedValue="{Binding Path=FUEL_TYPE, Mode=TwoWay}" Width="120">
 
                         </ComboBox>
                      </DataTemplate>
             </sdk:DataGridTemplateColumn.CellEditingTemplate>
        </sdk:DataGridTemplateColumn>
...

4. One last item, notice the datagrid’s current cell changed event is wired up to start editing without requiring the user to click first.  That method is simple enough:

private void dgMyDataGrid_CurrentCellChanged(object sender, EventArgs e)
  {
      dgMyDataGrid.BeginEdit();
  }

 

 

That gives me my datagrid with my combo box:

image

 

 

Here is a sample solution that has the full code: 

 ComboBoxTest.zip (1,016.17 kb)

Tags:

Development | Silverlight

Comments (11) -

Julien L.
Julien L. Belgium
10/4/2011 5:37:18 AM #

After trying a lot of tutorial without result, I tryed this one. It works perfect, at the first compilation...
Thanks a lot, you really helped me!

David
David United States
1/5/2012 2:49:21 PM #

I followed the instructions but it doesn't work for me. The grid seems OK but doesn't have any rows in it. Normally I would add rows to a datagrid (at least an autogenerate rows datagrid) by creating a list<T> (where T is a class with e.g. public string elements), adding a T to the list, and setting the datagrid.ItemsSource = the list<T>.

What am I missing here - how is the initial row supposed to be generated?

jbrooks
jbrooks United States
1/5/2012 6:46:05 PM #

Yes, for a simple demo you would need to bind this to a list that had a property of FUEL_TYPE
Something like List<Test>

public class Test
    {
        public string FUEL_TYPE { get; set; }
    }

David
David United States
1/6/2012 11:51:01 AM #

I added this:
        public class Test
        {
            public string FUEL_TYPE {get; set;}
        }

        private void AddEmptyRowtoGrid()
        {
            Test test = new Test();
            List<Test> source = (List<Test>)dgMyDataGrid.ItemsSource;

            if (source == null || source.Count == 0)
                source = new List<Test>();

            source.Add(test);
            dgMyDataGrid.ItemsSource = source;
        }

I'm getting a null resource exception. I noticed that Test::FUEL_TYPE is null, so I added a ctor and initialized FUEL_TYPE,  but I still get the same result. I also noticed that this XAML definition is problematic (I think this is the real problem):

                            <ComboBox Height="23" Name="cbxFuelType"
                                 ItemsSource="{StaticResource FuelList}"
                                 SelectedValue="{Binding Path=FUEL_TYPE, Mode=TwoWay}" Width="120">
                            </ComboBox>

In the definition: ItemsSource="{StaticResource FuelList}", the XAML editor tells me that "the resource "FuelList" could not be resolved". How do I resolve this?

jbrooks
jbrooks United States
1/8/2012 2:07:02 PM #

You never populated the property FUEL_TYPE.  Maybe try
Test test = new Test() { FUEL_TYPE = "Gas"};

David
David United States
1/16/2012 1:49:03 PM #

Hi,
I tried again, still same null resource exception. I have initialized the Test::FUEL_TYPE, so this is something else. I think the problem is here:

                            <ComboBox Height="23" Name="cbxFuelType"
                                 ItemsSource="{StaticResource FuelList}"
                                 SelectedValue="{Binding Path=FUEL_TYPE, Mode=TwoWay}" Width="120">
                            </ComboBox>

In the definition: ItemsSource="{StaticResource FuelList}", the XAML editor tells me that "the resource "FuelList" could not be resolved". How do I resolve this? I think I need a local namespace qualifier on FuelList?

Thx

jbrooks
jbrooks United States
1/17/2012 8:53:02 AM #

I added a sample solution that has the code and works.

Jay
Jay United States
3/7/2012 4:16:31 AM #

Please help....trying this example and I get error in xaml on ItemsSource="{StaticResource FuelList}"   seen below...I am converting to VB
Error: "The Resource Fuel List cannot be resolved"

<ComboBox Height="23" Name="cbxFuelType"                                  
         ItemsSource="{StaticResource FuelList}"                                  
         SelectedValue="{Binding Path=FUEL_TYPE, Mode=TwoWay}" Width="120"></ComboBox>

The code still runs but when I click on one of the records in the datagrid I get an error and it points to : dgMyDataGrid.BeginEdit() in the code below
Error: Cannot find a Resource with the Name/Key FuelList [Line: 756 Position: 71]

    Private Sub dgMyDataGrid_CurrentCellChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
        dgMyDataGrid.BeginEdit()

    End Sub

jbrooks
jbrooks United States
3/7/2012 1:07:41 PM #

Email me your code.  Jim

Jay
Jay United States
3/8/2012 5:41:49 AM #

Thanks Jim....I sent you my code that I am trying in a message from the Contact Link at the top of the page.
Thank very much for your help....its greatly appreciated...I cannto believe I am havign such a hard time with a simple combobox...

jbrooks
jbrooks United States
3/10/2012 4:44:56 AM #

Jay,
    The line:
              Me.Resources.Add("FuelList", FuelList)
    
    must be done before the line:
              InitializeComponent();

You have it the other way.
Jim