user896692
user896692

Reputation: 2371

WPF Binding Repository and Model

I´ve got two classes, Handy(It´s a Model with ID, Name and Year) and a HandyRepository.

My HandyRepository looks like this:

 private IList<Handy> list = new List<Handy>(new Handy[] {
        new Handy{ ID=1, Name="Nokia ", Jahr=1999},
        new Handy{ ID=2, Name="HTC m", Jahr=2333},
        new Handy{ ID=3, Name="Samsung", Jahr=2134} });


    public IEnumerable<Handy> GetList()
    {
        return this.list;
    }

Now, i want that data to a ListBox in my wpf-application, without writing any code in the code-behind file.

My attempt:

    xmlns:local="clr-namespace:Handy"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <Grid.DataContext>
        <local:Handy></local:Handy>
    </Grid.DataContext>

    <ListBox Name="lbBinding" ItemsSource="{Binding Name}"></ListBox>
</Grid>

That doesn´t work. Do I have a basic error in reasoning? How can I solve this problem?

Upvotes: 1

Views: 690

Answers (1)

Matthew Walton
Matthew Walton

Reputation: 9969

You haven't managed to bind ItemsSource to the actual collection. Firstly, you need to make a collection and give it a key by which it can be identified:

<x:Array x:Key="HandyList" Type="{x:Type local:Handy}">
    <local:Handy Name="Nokia " Jahr="1999" ID="1" />
    <local:Handy Name="HTC m", Jahr="2333" ID="2" />
</x:Array>

The key can be any identifier you like.

Then you need to tell the ListBox to look for that key:

<ListBox ItemsSource="{StaticResource HandyList}" Name="lbBinding" />

Unfortunately that won't render entirely correctly, as you'll get the default ToString() of the Handy class appearing in the ListBox, so you need to tell it how to render:

<ListBox ItemsSource="{StaticResource HandyList}"
         Name="lbBinding"
         DisplayMemberPath="Name" />

That will ensure it uses the Name property as the source of the string to render in the ListBox. You can do more complicated rendering by providing a custom DataTemplate if you need it.

Of course, there are few real-world applications where you define your ItemsSource in the XAML. It's more normal to bind to a property of the view's DataContext. The simplest way to do that would be to add a property to the view itself in its codebehind:

public List<Handy> HandyList { get; set; }

Then set the view to be its own DataContext in its constructor, after the call to InitializeComponent():

DataContext = this;

Then you can bind ItemsSource in the XAML to {Binding Path=HandyList}. Don't forget to construct the list and populate it, of course...

Upvotes: 1

Related Questions