Stefi Pallo
Stefi Pallo

Reputation: 111

WPF Binding observablecollection to listbox

I have a little problem and I don't know how to solve it. I have a class named Points that have an observable collection of System.Windows Point. It looks like this:

public class Points
{
    public Points()
    {
        MyPoints = new ObservableCollection<Point>();
        InitWithValues();
    }

    public ObservableCollection<Point> MyPoints { get; set; }

    private void InitWithValues()
    {
        MyPoints.Add(new Point(1, 2));
        MyPoints.Add(new Point(3, 4));
    }
}

Now I want to put this collection on a usercontrol into a listbox with textboxes. Here is the xaml:

<Grid Background="Gainsboro">
    <ListBox Name="Box">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Grid Background="Gainsboro">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*"/>
                        <ColumnDefinition Width="*"/>
                    </Grid.ColumnDefinitions>
                    <TextBox 
                             Text="{Binding x}"
                             Grid.Column="0"
                             MinWidth="30" />
                    <TextBox Grid.Column="1" 
                             Text="{Binding y, Mode=TwoWay,   UpdateSourceTrigger=PropertyChanged}"
                             MinWidth="30"/>
                </Grid>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Grid>

And the code behind:

public partial class MainWindow
{
    public Points points { get; set; }
    public ObservableCollection<Point> DataPoints { get; set; } 
    public MainWindow()
    {
        InitializeComponent();
        points = new Points();
        DataPoints=new ObservableCollection<Point>();
        foreach (Point point in points.MyPoints)
        {
            DataPoints.Add(point);
        }
        Box.ItemsSource = DataPoints;
        DataContext = this;
    }
}

When I run this code I get a window with two rows - one for each point and two text boxes on each row - for x and for y. But the text boxes are empty and I don't know what I'm doing wrong (each text box should contain x - left text box and y - right text box for a point).....here is a print screen with the result

Can anyone give me an advice? Thanks!

Upvotes: 0

Views: 325

Answers (1)

Rohit Vats
Rohit Vats

Reputation: 81253

Property names are case sensitive. You are binding to x instead of X and same for y and Y.

Change property name in binding to this:

Text="{Binding X}"

and

Text="{Binding Y}"

Upvotes: 1

Related Questions