Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Datagrid binding to list problems

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!

like image 970
baron Avatar asked Jan 25 '10 01:01

baron


2 Answers

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.

like image 181
lesscode Avatar answered Oct 07 '22 12:10

lesscode


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

like image 38
kenwarner Avatar answered Oct 07 '22 11:10

kenwarner