views:

1934

answers:

2

I have a list of custom objects: say Fruits with two string properties Name and Color. These are in a List.

private readonly List<Fruit> fruitList = new List<Fruit>();

Then I load fruit objects into the list.

I am trying to bind this list to WPF Datagrid:

C#:

dgFruit.ItemsSource = "{Binding}";

XAML:

<toolkit:DataGrid Name="dgFruit" 
            ItemsSource="{Binding Path=fruitList}" >
                <toolkit:DataGrid.Columns>

                    <toolkit:DataGridComboBoxColumn 
            Header="Name" 
            SelectedValueBinding="{Binding Path=Name}" 
            TextBinding="{Binding Path=Name}" Width="5*" />   

                    <toolkit:DataGridComboBoxColumn 
            Header="Color"
            SelectedValueBinding="{Binding Path=Color}"
            TextBinding="{Binding Path=Color}" Width="5*" />

                </toolkit:DataGrid.Columns>
            </toolkit:DataGrid>

Reason they are in a combobox is because I want user to be able to change the relationship. This is not the real example but you get the idea. Say for the sake of the example the fruit wasn't ripe so they change Banana color to green :)

I'm not having any luck getting these items in the datagrid... and down the track, I want a click on the item in the datagridcell to change to combobox and show all possible types of Fruit Names and Colors (so they can change the relationships)

Here is an error i'm getting:

System.Windows.Data Error: 39 : BindingExpression path error: 'Color' property not found on 'object' ''Char' (HashCode=6750311)'. BindingExpression:Path=Color; DataItem='Char' (HashCode=6750311); target element is 'TextBlockComboBox' (Name=''); target property is 'Text' (type 'String')

Can anyone help? The reason i am setting my colums up in xaml is so i can set width to star size and have the columns equal width.

I see most examples use an ObservableCollection but if I can bind to list why do I have to use this?

Please let me knwo if my example requires further clarification

Edit: what I have now:

XAML:

            <toolkit:DataGrid Name="dgFruit" 
            ItemsSource="{Binding}"
            AutoGenerateColumns="False">

                <toolkit:DataGrid.Columns>
                    <toolkit:DataGridTextColumn 
                        Header="Name"
                        Width="5*"/>

                    <toolkit:DataGridComboBoxColumn 
            Header="Color"
            Width="5*"/>

                    </toolkit:DataGrid.Columns>
</toolkit:DataGrid>

C#:

DataContext = fruitList;

Actually when I use DataContext I get no items. When I use ItemSource I get blank lines, but the correct number of rows so this seems more along the right lines.

I can get the data to show if I let it Auto generate columns. If I set autogeneratecolumns to false and then specify my columns in xaml like i want to to use star sizing, I get the right number of columns but no text!

+2  A: 

WPF doesn't support binding to fields. Create a property that accesses fruitList and bind to that.

    // this is the field. you can't bind to this
    private readonly List<Fruit> fruitList = new List<Fruit>();

    // this is the property. you can bind to this
    public List<Fruit> FruitList
    {
        get { return fruitList; }
    }

Use dgFruit.DataContext = this; instead of dgFruit.ItemsSource = "{Binding}";

And if you want to show these in a ComboBox, you need to bind those DataGridComboBoxColumn to a list of colors, not just a string. For example, your class might look like

public class Fruit
{
    public string Name { get; set; }
    public string Color { get; set; } // bind the combobox selectedvalue to this

    public List<string> AvailableColors { get; set; } // bind the combobox ItemsSource to this
}

And you can use a List if you like. The advantage of ObservableCollection is it already implements INotifyCollectionChanged and INotifyPropertyChanged for you

qntmfred
I don't understand what you mean by creating a property that accesses fruitlist. I guess I could use ObservableCollection just that I use lists everywhere else.And I undestand it needs to be a list. I want that list to be all the values in Fruit.Color or Fruit.Name. The gridview shuold show the original relation, i.e. Apple -> Red and Banana -> Yellow are the values but if I double click Apple I see the combo with all options of fruit objects, so Apple and Banana, and similarly with the Color...
baron
+1  A: 

First, this:

dgFruit.ItemsSource = "{Binding}"

should set the items source to a string containing the word Binding in braces. This is almost certainly not what you want (in fact, if you do this you should end up with a grid with nine rows, one for each character in the string!). You can set the ItemsSource in the XAML, or the code behind, but you shouldn't do both. Try the following:

<toolkit:DataGrid Name="dgFruit"       
                  ItemsSource="{Binding}">
    ...
</toolkit:DataGrid>

And then in your visual's constructor:

...
    InitializeComponents();
    this.DataContext = fruitList;
...

Now the data context for your whole visual is the List<Fruit>, and the ItemsSource of your grid is set to be the same object. I'm assuming here that fruitList is a field of the visual itself.

The bindings for your columns should look something like:

        <toolkit:DataGridTextColumn Header="Name"
                                    Binding="{Binding Name}"
                                    Width="5*" />
        <toolkit:DataGridComboBoxColumn Header="Color"
                                        ItemsSource="{Binding Source={StaticResource AllColors}}"
                                        SelectedValueBinding="{Binding Path=Color}"
                                        TextBinding="{Binding Path=Color}"
                                        Width="5*" />

Where AllColors is defined as a resource (in this case):

<x:Array x:Key="AllColors"
         Type="sys:String">
    <sys:String>Orange</sys:String>
    <sys:String>Yellow</sys:String>
</x:Array>

This should get you started.

Wayne
it owrks but when I do this the columns I define in xaml are ignored and it adds new ones to the left. Can I programatically set star sizes for these auto generated columns?
baron
You can turn off the auto-generated ones. On your DataGrid in XAML:AutoGenerateColumns="False"
Wayne
getting closer, now no items show though :( see recent edit
baron
See edited answer
Wayne
Thanks! I dont know how I didn't try that the other day - tried like a thousand variations, but that's got it. Think I probably need to read up a bit more on data binding.
baron