Renet
Renet

Reputation: 349

Display a ListView row in a label

I have a ListView in WPF that is getting data from a database. I want it that, when i have a column selected, and press a button, it will display a row as label.content. Here's what I have this far but it wont work(i removed some items like height etc from it atm):

<ListView x:Name="listView" HorizontalAlignment="Left" VerticalAlignment="Top">
        <ListView.View>
            <GridView>
                <GridViewColumn DisplayMemberBinding="{Binding Path=Item1}" Header="Item1"/>
                <GridViewColumn DisplayMemberBinding="{Binding Path=Item2}" Header="Item2"/>
                <GridViewColumn DisplayMemberBinding="{Binding Path=Item3}" Header="Item3"/>
            </GridView>
        </ListView.View>

And then in the code behind part:

    DataRowView dataRow;
    int indexInt;

    indexInt = listView.SelectedIndex;
    dataRow = listView.Items.GetItemAt(indexInt) as DataRowView;

    if(dataRow!=null)
    {
         labelOne.Content = (dataRow["Item2"]);
    }

If i remove the datarow!=null check, it will display this error: Object reference not set to an instance of an object.

Can anyone help me fix this or should I approach it in another way?

Upvotes: 2

Views: 880

Answers (1)

Louis Kottmann
Louis Kottmann

Reputation: 16628

You should use an MVVM approach:

--> your ListView's ItemsSource property should be bound to the collection being displayed.
--> (OPTIONAL) your ListView's SelectedValue property should be bound to a property in your ViewModel, let's call it CurrentRow.
--> labelOne's Content property should be bound to CurrentRow (or listView.SelectedValue.Item2 if you didn't do the optional step)

And you won't have to tinker with UI elements from code behind anymore (which is usually a sign of bad practice).
In fact, you probably won't need to name your controls anymore either.

It should look like this:

<Label name="labelOne" Content="{Binding SelectedValue.Item2, ElementName=listView}" />
<ListView x:Name="listView" HorizontalAlignment="Left" VerticalAlignment="Top">
        <ListView.View>
            <GridView>
                <GridViewColumn DisplayMemberBinding="{Binding Path=Item1}" Header="Item1"/>
                <GridViewColumn DisplayMemberBinding="{Binding Path=Item2}" Header="Item2"/>
                <GridViewColumn DisplayMemberBinding="{Binding Path=Item3}" Header="Item3"/>
            </GridView>
        </ListView.View>

Upvotes: 1

Related Questions