Pouyan
Pouyan

Reputation: 2939

ListView SelectedValue in WPF

I have a ListView in my WPF application. my ListViewItem s are just Images. but I want to get the selected value of this ListView. In ASP.Net I can set a Text/Value pair for a listitem, and the selectedvalue was the Value I have set.

how can I achieve this in wpf ?

Here is my Xaml :

<ListView Name="lstStyle" MouseDoubleClick="lstStyle_MouseDoubleClick" KeyDown="lstStyle_KeyDown">
        <ListViewItem>
            <Image Source="/WPFSample;component/Images/Home1.png"></Image>

        </ListViewItem>

Any Idea ?

Upvotes: 0

Views: 2147

Answers (2)

Maurizio Reginelli
Maurizio Reginelli

Reputation: 3212

Your ListView items should be in binding with a collection in the DataContext. To do that you can use the property ItemsSource. Anoher property, called SelectedItem, can be used to bind the selected item in the ListView to another property in your DataContext.

Upvotes: 0

Rachel
Rachel

Reputation: 132558

Use the ListView's ItemsSource and bind it to a collection of objects containing your image path and your Id field

<ListView ItemsSource="{Binding MyCollection}"
          SelectedValuePath="Id"
          SelectedValue="{Binding SelectedId}">

    <ListView.ItemTemplate>
        <DataTemplate>
            <Image Source="{Binding ImagePath}" />
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

In your ListView's DataContext you would have

public ObservableCollection<MyItem> MyCollection;
public int SelectedId;

where MyItem is simply a class that looks like this:

public class MyItem
{
    public int Id { get; set; }
    public string ImagePath { get; set; }
}

Or as an alternative, if you're not interested in good design, just use the Tag property of the ListViewItem

<ListViewItem Tag="1">

Upvotes: 1

Related Questions